Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Text
Imports System.IO

Public Enum DialogStatus
    Ok
    Abort
    Skip
End Enum

Public Class Support
    Public Shared OverwriteALL As Boolean = True

    Public Shared Function SplitList(ByVal InputString As String, ByVal CharactersToDelimitWith As String) As ArrayList
        Dim CurrentIndex As Integer
        SplitList = New ArrayList

        Dim CurrentToken As String = ""
        For CurrentIndex = 0 To InputString.Length - 1
            If InStr(CharactersToDelimitWith, InputString(CurrentIndex).ToString) > 0 Then
                If CurrentToken.Length > 0 Then
                    SplitList.Add(CurrentToken)
                    CurrentToken = ""
                End If
            Else
                CurrentToken = CurrentToken & InputString(CurrentIndex).ToString
            End If
        Next

        If CurrentToken.Length > 0 Then
            SplitList.Add(CurrentToken)
        End If

        Return SplitList
    End Function


    Public Shared Function DownloadFile(ByVal TableGen As RawCreateScript, ByVal BasePath As String, ByVal txt As TextBox) As Boolean
        Dim Extension As String = ""
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                Extension = "vb"
            Case CodeTypeEnum.CS2005
                Extension = "cs"
        End Select

        Dim AE As New ASCIIEncoding()

        Dim cMasterASPX As New MasterASPX(TableGen)
        Dim MasterASPX As String = cMasterASPX.ToString()
        cMasterASPX = Nothing

        Dim fs As System.IO.FileStream
        Try

            fs = New System.IO.FileStream(BasePath & TableGen.OutputFileName & ".aspx", FileMode.Create)
        Catch ex As Exception
            MsgBox(ex.ToString)
            Return False
        End Try

        txt.Text = "Created " & BasePath & TableGen.OutputFileName & ".aspx" & vbCrLf & txt.Text
        Dim out As Byte() = AE.GetBytes(MasterASPX)
        fs.Write(out, 0, out.Length)
        fs.Close()

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005, CodeTypeEnum.CS2005
                Dim MasterASPXVB As New MasterASPXVB(TableGen)
                Dim FileName As String = BasePath & TableGen.OutputFileName & ".aspx." & Extension
                Dim SkipThisFile As Boolean = False


                If System.IO.File.Exists(FileName) Then
                    If OverwriteALL Then
                        If IsFileReadOnly(FileName) Then
                            UnWriteProtectFile(FileName)
                        End If
                    Else

                    End If
                End If


                If SkipThisFile = False Then
                    fs = New FileStream(FileName, FileMode.Create)
                    txt.Text = "Created " & FileName & vbCrLf & txt.Text
                    out = AE.GetBytes(MasterASPXVB.ToString)
                    fs.Write(out, 0, out.Length)
                    fs.Close()
                End If
        End Select

        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
            Case Else
                Dim DetailASPX As New DetailASPX(TableGen)
                Dim DetailASPXText As String = DetailASPX.ToString

                fs = New FileStream(BasePath & "Edit" & TableGen.OutputFileName & ".aspx", FileMode.Create)
                txt.Text = "Created " & BasePath & "Edit" & TableGen.OutputFileName & ".aspx" & vbCrLf & txt.Text
                out = AE.GetBytes(DetailASPXText)
                fs.Write(out, 0, out.Length)
                fs.Close()

                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005, CodeTypeEnum.CS2005

                        Dim Detailaspxvb As New DetailASPXVB(TableGen)
                        Dim DetailASPXVBText As String = Detailaspxvb.ToString

                        fs = New FileStream(BasePath & "Edit" & TableGen.OutputFileName & ".aspx." & Extension, FileMode.Create)
                        txt.Text = "Created " & BasePath & "Edit" & TableGen.OutputFileName & ".aspx." & Extension & vbCrLf & txt.Text
                        out = AE.GetBytes(DetailASPXVBText)
                        fs.Write(out, 0, out.Length)
                        fs.Close()
                End Select
        End Select
        Return True

 


    End Function

    Public Shared Function FixWriteProtection(ByVal FileName As String) As DialogStatus


    End Function

    Public Shared Function IsFileReadOnly(ByVal FileName As String) As Boolean
        IsFileReadOnly = False
        Dim FA As FileAttributes = System.IO.File.GetAttributes(FileName)
        If FA And FileAttribute.ReadOnly Then
            IsFileReadOnly = True
        End If
    End Function

    Public Shared Sub UnWriteProtectFile(ByVal FileName As String)
        Dim FA As FileAttributes = System.IO.File.GetAttributes(FileName)
        System.IO.File.SetAttributes(FileName, FA And (Not FileAttribute.ReadOnly))
    End Sub


    Private Shared Function GetDatePickerJS() As String
        Dim sb As New StringBuilder

        sb.AppendLine("var datePickerDivID = ""datepicker"";")
        sb.AppendLine("var iFrameDivID = ""datepickeriframe"";")
        sb.AppendLine("")
        sb.AppendLine("var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');")
        sb.AppendLine("var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');")
        sb.AppendLine("var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');")
        sb.AppendLine("var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');")
        sb.AppendLine("var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');")
        sb.AppendLine("var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');")
        sb.AppendLine(" ")
        sb.AppendLine("// these variables define the date formatting we're expecting and outputting.")
        sb.AppendLine("// If you want to use a different format by default, change the defaultDateSeparator")
        sb.AppendLine("// and defaultDateFormat variables either here or on your HTML page.")
        sb.AppendLine("var defaultDateSeparator = ""/"";        // common values would be ""/"" or "".""")
        sb.AppendLine("var defaultDateFormat = ""mdy""    // valid values are ""mdy"", ""dmy"", and ""ymd""")
        sb.AppendLine("var dateSeparator = defaultDateSeparator;")
        sb.AppendLine("var dateFormat = defaultDateFormat;")
        sb.AppendLine("")
        sb.AppendLine("function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)")
        sb.AppendLine("{")
        sb.AppendLine("  var targetDateField = document.getElementsByName (dateFieldName).item(0);")
        sb.AppendLine(" ")
        sb.AppendLine("  // if we weren't told what node to display the datepicker beneath, just display it")
        sb.AppendLine("  // beneath the date field we're updating")
        sb.AppendLine("  if (!displayBelowThisObject)")
        sb.AppendLine("    displayBelowThisObject = targetDateField;")
        sb.AppendLine(" ")
        sb.AppendLine("  // if a date separator character was given, update the dateSeparator variable")
        sb.AppendLine("  if (dtSep)")
        sb.AppendLine("    dateSeparator = dtSep;")
        sb.AppendLine("  else")
        sb.AppendLine("    dateSeparator = defaultDateSeparator;")
        sb.AppendLine(" ")
        sb.AppendLine("  // if a date format was given, update the dateFormat variable")
        sb.AppendLine("  if (dtFormat)")
        sb.AppendLine("    dateFormat = dtFormat;")
        sb.AppendLine("  else")
        sb.AppendLine("    dateFormat = defaultDateFormat;")
        sb.AppendLine(" ")
        sb.AppendLine("  var x = displayBelowThisObject.offsetLeft;")
        sb.AppendLine("  var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;")
        sb.AppendLine(" ")
        sb.AppendLine("  // deal with elements inside tables and such")
        sb.AppendLine("  var parent = displayBelowThisObject;")
        sb.AppendLine("  while (parent.offsetParent) {")
        sb.AppendLine("    parent = parent.offsetParent;")
        sb.AppendLine("    x += parent.offsetLeft;")
        sb.AppendLine("    y += parent.offsetTop ;")
        sb.AppendLine("  }")
        sb.AppendLine(" ")
        sb.AppendLine("  drawDatePicker(targetDateField, x, y);")
        sb.AppendLine("}")
        sb.AppendLine("")
        sb.AppendLine("")
        sb.AppendLine("/**")
        sb.AppendLine("Draw the datepicker object (which is just a table with calendar elements) at the")
        sb.AppendLine("specified x and y coordinates, using the targetDateField object as the input tag")
        sb.AppendLine("that will ultimately be populated with a date.")
        sb.AppendLine("")
        sb.AppendLine("This function will normally be called by the displayDatePicker function.")
        sb.AppendLine("*/")
        sb.AppendLine("function drawDatePicker(targetDateField, x, y)")
        sb.AppendLine("{")
        sb.AppendLine("  var dt = getFieldDate(targetDateField.value );")
        sb.AppendLine(" ")
        sb.AppendLine("  // the datepicker table will be drawn inside of a <div> with an ID defined by the")
        sb.AppendLine("  // global datePickerDivID variable. If such a div doesn't yet exist on the HTML")
        sb.AppendLine("  // document we're working with, add one.")
        sb.AppendLine("  if (!document.getElementById(datePickerDivID)) {")
        sb.AppendLine("    // don't use innerHTML to update the body, because it can cause global variables")
        sb.AppendLine("    // that are currently pointing to objects on the page to have bad references")
        sb.AppendLine("    //document.body.innerHTML += ""<div id='"" + datePickerDivID + ""' class='dpDiv'></div>"";")
        sb.AppendLine("    var newNode = document.createElement(""div"");")
        sb.AppendLine("    newNode.setAttribute(""id"", datePickerDivID);")
        sb.AppendLine("    newNode.setAttribute(""class"", ""dpDiv"");")
        sb.AppendLine("    newNode.setAttribute(""style"", ""visibility: hidden;"");")
        sb.AppendLine("    document.body.appendChild(newNode);")
        sb.AppendLine("  }")
        sb.AppendLine(" ")
        sb.AppendLine("  // move the datepicker div to the proper x,y coordinate and toggle the visiblity")
        sb.AppendLine("  var pickerDiv = document.getElementById(datePickerDivID);")
        sb.AppendLine("  pickerDiv.style.position = ""absolute"";")
        sb.AppendLine("  pickerDiv.style.left = x + ""px"";")
        sb.AppendLine("  pickerDiv.style.top = y + ""px"";")
        sb.AppendLine("  pickerDiv.style.visibility = (pickerDiv.style.visibility == ""visible"" ? ""hidden"" : ""visible"");")
        sb.AppendLine("  pickerDiv.style.display = (pickerDiv.style.display == ""block"" ? ""none"" : ""block"");")
        sb.AppendLine("  pickerDiv.style.zIndex = 10000;")
        sb.AppendLine(" ")
        sb.AppendLine("  // draw the datepicker table")
        sb.AppendLine("  refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());")
        sb.AppendLine("}")
        sb.AppendLine("")
        sb.AppendLine("")
        sb.AppendLine("/**")
        sb.AppendLine("This is the function that actually draws the datepicker calendar.")
        sb.AppendLine("*/")
        sb.AppendLine("function refreshDatePicker(dateFieldName, year, month, day)")
        sb.AppendLine("{")
        sb.AppendLine("  // if no arguments are passed, use today's date; otherwise, month and year")
        sb.AppendLine("  // are required (if a day is passed, it will be highlighted later)")
        sb.AppendLine("  var thisDay = new Date();")
        sb.AppendLine(" ")
        sb.AppendLine("  if ((month >= 0) && (year > 0)) {")
        sb.AppendLine("    thisDay = new Date(year, month, 1);")
        sb.AppendLine("  } else {")
        sb.AppendLine("    day = thisDay.getDate();")
        sb.AppendLine("    thisDay.setDate(1);")
        sb.AppendLine("  }")
        sb.AppendLine(" ")
        sb.AppendLine("  // the calendar will be drawn as a table")
        sb.AppendLine("  // you can customize the table elements with a global CSS style sheet,")
        sb.AppendLine("  // or by hardcoding style and formatting elements below")
        sb.AppendLine("  var crlf = ""\r\n"";")
        sb.AppendLine("  var TABLE = ""<table cols=7 class='dpTable'>"" + crlf;")
        sb.AppendLine("  var xTABLE = ""</table>"" + crlf;")
        sb.AppendLine("  var TR = ""<tr class='dpTR'>"";")
        sb.AppendLine("  var TR_title = ""<tr class='dpTitleTR'>"";")
        sb.AppendLine("  var TR_days = ""<tr class='dpDayTR'>"";")
        sb.AppendLine("  var TR_todaybutton = ""<tr class='dpTodayButtonTR'>"";")
        sb.AppendLine("  var xTR = ""</tr>"" + crlf;")
        sb.AppendLine("  var TD = ""<td class='dpTD' onMouseOut='this.className=\""dpTD\"";' onMouseOver=' this.className=\""dpTDHover\"";' "";    // leave this tag open, because we'll be adding an onClick event")
        sb.AppendLine("  var TD_title = ""<td colspan=5 class='dpTitleTD'>"";")
        sb.AppendLine("  var TD_buttons = ""<td class='dpButtonTD'>"";")
        sb.AppendLine("  var TD_todaybutton = ""<td colspan=7 class='dpTodayButtonTD'>"";")
        sb.AppendLine("  var TD_days = ""<td class='dpDayTD'>"";")
        sb.AppendLine("  var TD_selected = ""<td class='dpDayHighlightTD' onMouseOut='this.className=\""dpDayHighlightTD\"";' onMouseOver='this.className=\""dpTDHover\"";' "";    // leave this tag open, because we'll be adding an onClick event")
        sb.AppendLine("  var xTD = ""</td>"" + crlf;")
        sb.AppendLine("  var DIV_title = ""<div class='dpTitleText'>"";")
        sb.AppendLine("  var DIV_selected = ""<div class='dpDayHighlight'>"";")
        sb.AppendLine("  var xDIV = ""</div>"";")
        sb.AppendLine(" ")
        sb.AppendLine("  // start generating the code for the calendar table")
        sb.AppendLine("  var html = TABLE;")
        sb.AppendLine(" ")
        sb.AppendLine("  // this is the title bar, which displays the month and the buttons to")
        sb.AppendLine("  // go back to a previous month or forward to the next month")
        sb.AppendLine("  html += TR_title;")
        sb.AppendLine("  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, ""&lt;"") + xTD;")
        sb.AppendLine("  html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + "" "" + thisDay.getFullYear() + xDIV + xTD;")
        sb.AppendLine("  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, ""&gt;"") + xTD;")
        sb.AppendLine("  html += xTR;")
        sb.AppendLine(" ")
        sb.AppendLine("  // this is the row that indicates which day of the week we're on")
        sb.AppendLine("  html += TR_days;")
        sb.AppendLine("  for(i = 0; i < dayArrayShort.length; i++)")
        sb.AppendLine("    html += TD_days + dayArrayShort[i] + xTD;")
        sb.AppendLine("  html += xTR;")
        sb.AppendLine(" ")
        sb.AppendLine("  // now we'll start populating the table with days of the month")
        sb.AppendLine("  html += TR;")
        sb.AppendLine(" ")
        sb.AppendLine("  // first, the leading blanks")
        sb.AppendLine("  for (i = 0; i < thisDay.getDay(); i++)")
        sb.AppendLine("    html += TD + ""&nbsp;"" + xTD;")
        sb.AppendLine(" ")
        sb.AppendLine("  // now, the days of the month")
        sb.AppendLine("  do {")
        sb.AppendLine("    dayNum = thisDay.getDate();")
        sb.AppendLine("    TD_onclick = "" onclick=\""updateDateField('"" + dateFieldName + ""', '"" + getDateString(thisDay) + ""');\"">"";")
        sb.AppendLine("    ")
        sb.AppendLine("    if (dayNum == day)")
        sb.AppendLine("      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;")
        sb.AppendLine("    else")
        sb.AppendLine("      html += TD + TD_onclick + dayNum + xTD;")
        sb.AppendLine("    ")
        sb.AppendLine("    // if this is a Saturday, start a new row")
        sb.AppendLine("    if (thisDay.getDay() == 6)")
        sb.AppendLine("      html += xTR + TR;")
        sb.AppendLine("    ")
        sb.AppendLine("    // increment the day")
        sb.AppendLine("    thisDay.setDate(thisDay.getDate() + 1);")
        sb.AppendLine("  } while (thisDay.getDate() > 1)")
        sb.AppendLine(" ")
        sb.AppendLine("  // fill in any trailing blanks")
        sb.AppendLine("  if (thisDay.getDay() > 0) {")
        sb.AppendLine("    for (i = 6; i > thisDay.getDay(); i--)")
        sb.AppendLine("      html += TD + ""&nbsp;"" + xTD;")
        sb.AppendLine("  }")
        sb.AppendLine("  html += xTR;")
        sb.AppendLine(" ")
        sb.AppendLine("  // add a button to allow the user to easily return to today, or close the calendar")
        sb.AppendLine("  var today = new Date();")
        sb.AppendLine("  var todayString = ""Today is "" + dayArrayMed[today.getDay()] + "", "" + monthArrayMed[ today.getMonth()] + "" "" + today.getDate();")
        sb.AppendLine("  html += TR_todaybutton + TD_todaybutton;")
        sb.AppendLine("  html += ""<table width='100%'><tr><td align='left'><button class='dpTodayButton' onClick='refreshDatePicker(\"""" + dateFieldName + ""\"");'>today</button></td>"";")
        sb.AppendLine("  html += ""<td align='right'><button class='dpTodayButton' onClick='updateDateField(\"""" + dateFieldName + ""\"");'>x</button></td></tr></table>"";")
        sb.AppendLine("  html += xTD + xTR;")
        sb.AppendLine(" ")
        sb.AppendLine("  // and finally, close the table")
        sb.AppendLine("  html += xTABLE;")
        sb.AppendLine(" ")
        sb.AppendLine("  document.getElementById(datePickerDivID).innerHTML = html;")
        sb.AppendLine("  // add an ""iFrame shim"" to allow the datepicker to display above selection lists")
        sb.AppendLine("  adjustiFrame();")
        sb.AppendLine("}")
        sb.AppendLine("")
        sb.AppendLine("")
        sb.AppendLine("/**")
        sb.AppendLine("Convenience function for writing the code for the buttons that bring us back or forward")
        sb.AppendLine("a month.")
        sb.AppendLine("*/")
        sb.AppendLine("function getButtonCode(dateFieldName, dateVal, adjust, label)")
        sb.AppendLine("{")
        sb.AppendLine("  var newMonth = (dateVal.getMonth () + adjust) % 12;")
        sb.AppendLine("  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);")
        sb.AppendLine("  if (newMonth < 0) {")
        sb.AppendLine("    newMonth += 12;")
        sb.AppendLine("    newYear += -1;")
        sb.AppendLine("  }")
        sb.AppendLine(" ")
        sb.AppendLine("  return ""<button class='dpButton' onClick='refreshDatePicker(\"""" + dateFieldName + ""\"", "" + newYear + "", "" + newMonth + "");'>"" + label + ""</button>"";")
        sb.AppendLine("}")
        sb.AppendLine("")
        sb.AppendLine("")
        sb.AppendLine("/**")
        sb.AppendLine("Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator")
        sb.AppendLine("variables at the beginning of this script library.")
        sb.AppendLine("*/")
        sb.AppendLine("function getDateString(dateVal)")
        sb.AppendLine("{")
        sb.AppendLine("  var dayString = ""00"" + dateVal.getDate();")
        sb.AppendLine("  var monthString = ""00"" + (dateVal.getMonth()+1);")
        sb.AppendLine("  dayString = dayString.substring(dayString.length - 2);")
        sb.AppendLine("  monthString = monthString.substring(monthString.length - 2);")
        sb.AppendLine(" ")
        sb.AppendLine("  switch (dateFormat) {")
        sb.AppendLine("    case ""dmy"" :")
        sb.AppendLine("      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();")
        sb.AppendLine("    case ""ymd"" :")
        sb.AppendLine("      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;")
        sb.AppendLine("    case ""mdy"" :")
        sb.AppendLine("    default :")
        sb.AppendLine("      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();")
        sb.AppendLine("  }")
        sb.AppendLine("}")
        sb.AppendLine("")
        sb.AppendLine("")
        sb.AppendLine("/**")
        sb.AppendLine("Convert a string to a JavaScript Date object.")
        sb.AppendLine("*/")
        sb.AppendLine("function getFieldDate(dateString)")
        sb.AppendLine("{")
        sb.AppendLine("  var dateVal;")
        sb.AppendLine("  var dArray;")
        sb.AppendLine("  var d, m, y;")
        sb.AppendLine(" ")
        sb.AppendLine("  try {")
        sb.AppendLine("    dArray = splitDateString(dateString);")
        sb.AppendLine("    if (dArray) {")
        sb.AppendLine("      switch (dateFormat) {")
        sb.AppendLine("        case ""dmy"" :")
        sb.AppendLine("          d = parseInt(dArray[0], 10);")
        sb.AppendLine("          m = parseInt(dArray[1], 10) - 1;")
        sb.AppendLine("          y = parseInt(dArray[2], 10);")
        sb.AppendLine("          break;")
        sb.AppendLine("        case ""ymd"" :")
        sb.AppendLine("          d = parseInt(dArray[2], 10);")
        sb.AppendLine("          m = parseInt(dArray[1], 10) - 1;")
        sb.AppendLine("          y = parseInt(dArray[0], 10);")
        sb.AppendLine("          break;")
        sb.AppendLine("        case ""mdy"" :")
        sb.AppendLine("        default :")
        sb.AppendLine("          d = parseInt(dArray[1], 10);")
        sb.AppendLine("          m = parseInt(dArray[0], 10) - 1;")
        sb.AppendLine("          y = parseInt(dArray[2], 10);")
        sb.AppendLine("          break;")
        sb.AppendLine("      }")
        sb.AppendLine("      dateVal = new Date(y, m, d);")
        sb.AppendLine("    } else if (dateString) {")
        sb.AppendLine("      dateVal = new Date(dateString);")
        sb.AppendLine("    } else {")
        sb.AppendLine("      dateVal = new Date();")
        sb.AppendLine("    }")
        sb.AppendLine("  } catch(e) {")
        sb.AppendLine("    dateVal = new Date();")
        sb.AppendLine("  }")
        sb.AppendLine(" ")
        sb.AppendLine("  return dateVal;")
        sb.AppendLine("}")
        sb.AppendLine("")
        sb.AppendLine("")
        sb.AppendLine("/**")
        sb.AppendLine("Try to split a date string into an array of elements, using common date separators.")
        sb.AppendLine("If the date is split, an array is returned; otherwise, we just return false.")
        sb.AppendLine("*/")
        sb.AppendLine("function splitDateString(dateString)")
        sb.AppendLine("{")
        sb.AppendLine("  var dArray;")
        sb.AppendLine("  if (dateString.indexOf(""/"") >= 0)")
        sb.AppendLine("    dArray = dateString.split(""/"");")
        sb.AppendLine("  else if (dateString.indexOf(""."") >= 0)")
        sb.AppendLine("    dArray = dateString.split(""."");")
        sb.AppendLine("  else if (dateString.indexOf(""-"") >= 0)")
        sb.AppendLine("    dArray = dateString.split(""-"");")
        sb.AppendLine("  else if (dateString.indexOf(""\\"") >= 0)")
        sb.AppendLine("    dArray = dateString.split(""\\"");")
        sb.AppendLine("  else")
        sb.AppendLine("    dArray = false;")
        sb.AppendLine(" ")
        sb.AppendLine("  return dArray;")
        sb.AppendLine("}")
        sb.AppendLine("")
        sb.AppendLine("")
        sb.AppendLine("function updateDateField(dateFieldName, dateString)")
        sb.AppendLine("{")
        sb.AppendLine("")
        sb.AppendLine("  var targetDateField = document.getElementsByName(dateFieldName).item(0);")
        sb.AppendLine("  if (dateString)")
        sb.AppendLine("    targetDateField.value = dateString;")
        sb.AppendLine(" ")
        sb.AppendLine("  var pickerDiv = document.getElementById(datePickerDivID);")
        sb.AppendLine("  pickerDiv.style.visibility = ""hidden"";")
        sb.AppendLine("  pickerDiv.style.display = ""none"";")
        sb.AppendLine(" ")
        sb.AppendLine("  adjustiFrame();")
        sb.AppendLine("  targetDateField.focus();")
        sb.AppendLine(" ")
        sb.AppendLine("  // after the datepicker has closed, optionally run a user-defined function called")
        sb.AppendLine("  // datePickerClosed, passing the field that was just updated as a parameter")
        sb.AppendLine("  // (note that this will only run if the user actually selected a date from the datepicker)")
        sb.AppendLine("  if ((dateString) && (typeof(datePickerClosed) == ""function""))")
        sb.AppendLine("    datePickerClosed(targetDateField);")
        sb.AppendLine("}")
        sb.AppendLine("")
        sb.AppendLine("")
        sb.AppendLine("function adjustiFrame(pickerDiv, iFrameDiv)")
        sb.AppendLine("{")
        sb.AppendLine("  var is_opera = (navigator.userAgent.toLowerCase().indexOf(""opera"") != -1);")
        sb.AppendLine("  if (is_opera)")
        sb.AppendLine("    return;")
        sb.AppendLine("  ")
        sb.AppendLine("  try {")
        sb.AppendLine("    if (!document.getElementById(iFrameDivID)) {")
        sb.AppendLine("      // don't use innerHTML to update the body, because it can cause global variables")
        sb.AppendLine("      // that are currently pointing to objects on the page to have bad references")
        sb.AppendLine("      //document.body.innerHTML += ""<iframe id='"" + iFrameDivID + ""' src='javascript:false;' scrolling='no' frameborder='0'>"";")
        sb.AppendLine("      var newNode = document.createElement(""iFrame"");")
        sb.AppendLine("      newNode.setAttribute(""id"", iFrameDivID);")
        sb.AppendLine("      newNode.setAttribute(""src"", ""javascript:false;"");")
        sb.AppendLine("      newNode.setAttribute(""scrolling"", ""no"");")
        sb.AppendLine("      newNode.setAttribute (""frameborder"", ""0"");")
        sb.AppendLine("      document.body.appendChild(newNode);")
        sb.AppendLine("    }")
        sb.AppendLine("    ")
        sb.AppendLine("    if (!pickerDiv)")
        sb.AppendLine("      pickerDiv = document.getElementById(datePickerDivID);")
        sb.AppendLine("    if (!iFrameDiv)")
        sb.AppendLine("      iFrameDiv = document.getElementById(iFrameDivID);")
        sb.AppendLine("    ")
        sb.AppendLine("    try {")
        sb.AppendLine("      iFrameDiv.style.position = ""absolute"";")
        sb.AppendLine("      iFrameDiv.style.width = pickerDiv.offsetWidth;")
        sb.AppendLine("      iFrameDiv.style.height = pickerDiv.offsetHeight ;")
        sb.AppendLine("      iFrameDiv.style.top = pickerDiv.style.top;")
        sb.AppendLine("      iFrameDiv.style.left = pickerDiv.style.left;")
        sb.AppendLine("      iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;")
        sb.AppendLine("      iFrameDiv.style.visibility = pickerDiv.style.visibility ;")
        sb.AppendLine("      iFrameDiv.style.display = pickerDiv.style.display;")
        sb.AppendLine("    } catch(e) {")
        sb.AppendLine("    }")
        sb.AppendLine(" ")
        sb.AppendLine("  } catch (ee) {")
        sb.AppendLine("  }")
        sb.AppendLine(" ")
        sb.AppendLine("}")

        Return sb.ToString
    End Function

    Private Shared Function GetDatePickerCSS() As String
        Dim sb As New StringBuilder
        sb.AppendLine("/* the div that holds the date picker calendar */")
        sb.AppendLine(".dpDiv {")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* the table (within the div) that holds the date picker calendar */")
        sb.AppendLine(".dpTable {")
        sb.AppendLine("    font-family: Tahoma, Arial, Helvetica, sans-serif;")
        sb.AppendLine("    font-size: 12px;")
        sb.AppendLine("    text-align: center;")
        sb.AppendLine("    color: #505050;")
        sb.AppendLine("    background-color: #ece9d8;")
        sb.AppendLine("    border: 1px solid #AAAAAA;")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* a table row that holds date numbers (either blank or 1-31) */")
        sb.AppendLine(".dpTR {")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* the top table row that holds the month, year, and forward/backward buttons */")
        sb.AppendLine(".dpTitleTR {")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* the second table row, that holds the names of days of the week (Mo, Tu, We, etc.) */")
        sb.AppendLine(".dpDayTR {")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* the bottom table row, that has the ""This Month"" and ""Close"" buttons */")
        sb.AppendLine(".dpTodayButtonTR {")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* a table cell that holds a date number (either blank or 1-31) */")
        sb.AppendLine(".dpTD {")
        sb.AppendLine("    border: 1px solid #ece9d8;")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* a table cell that holds a highlighted day (usually either today's date or the current date field value) */")
        sb.AppendLine(".dpDayHighlightTD {")
        sb.AppendLine("    background-color: #CCCCCC;")
        sb.AppendLine("    border: 1px solid #AAAAAA;")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* the date number table cell that the mouse pointer is currently over (you can use contrasting colors to make it apparent which cell is being hovered over) */")
        sb.AppendLine(".dpTDHover {")
        sb.AppendLine("    background-color: #aca998;")
        sb.AppendLine("    border: 1px solid #888888;")
        sb.AppendLine("    cursor: pointer;")
        sb.AppendLine("    color: red;")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* the table cell that holds the name of the month and the year */")
        sb.AppendLine(".dpTitleTD {")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* a table cell that holds one of the forward/backward buttons */")
        sb.AppendLine(".dpButtonTD {")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* the table cell that holds the ""This Month"" or ""Close"" button at the bottom */")
        sb.AppendLine(".dpTodayButtonTD {")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* a table cell that holds the names of days of the week (Mo, Tu, We, etc.) */")
        sb.AppendLine(".dpDayTD {")
        sb.AppendLine("    background-color: #CCCCCC;")
        sb.AppendLine("    border: 1px solid #AAAAAA;")
        sb.AppendLine("    color: white;")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* additional style information for the text that indicates the month and year */")
        sb.AppendLine(".dpTitleText {")
        sb.AppendLine("    font-size: 12px;")
        sb.AppendLine("    color: gray;")
        sb.AppendLine("    font-weight: bold;")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* additional style information for the cell that holds a highlighted day (usually either today's date or the current date field value) */ ")
        sb.AppendLine(".dpDayHighlight {")
        sb.AppendLine("    color: #4060ff;")
        sb.AppendLine("    font-weight: bold;")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* the forward/backward buttons at the top */")
        sb.AppendLine(".dpButton {")
        sb.AppendLine("    font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif;")
        sb.AppendLine("    font-size: 10px;")
        sb.AppendLine("    color: gray;")
        sb.AppendLine("    background: #d8e8ff;")
        sb.AppendLine("    font-weight: bold;")
        sb.AppendLine("    padding: 0px;")
        sb.AppendLine("    }")
        sb.AppendLine("")
        sb.AppendLine("/* the ""This Month"" and ""Close"" buttons at the bottom */")
        sb.AppendLine(".dpTodayButton {")
        sb.AppendLine("    font-family: Verdana, Tahoma, Arial, Helvetica, sans-serif;")
        sb.AppendLine("    font-size: 10px;")
        sb.AppendLine("    color: gray;")
        sb.AppendLine("    background: #d8e8ff;")
        sb.AppendLine("    font-weight: bold;")
        sb.AppendLine("    }")
        Return sb.ToString
    End Function

    Private Shared Function GetDetailASPXDesignerVB(ByVal TableGen As RawCreateScript) As String
        Dim sb As New StringBuilder

        sb.AppendLine("'''<summary>")
        sb.AppendLine("'''" & TableGen.TableName & " class.")
        sb.AppendLine("'''</summary>")
        sb.AppendLine("'''<remarks>")
        sb.AppendLine("'''Auto-generated class.")
        sb.AppendLine("'''</remarks>")
        sb.AppendLine("Partial public class Edit" & TableGen.TableName)
        sb.AppendLine()
        sb.AppendLine("    '''<summary>")
        sb.AppendLine("    '''form1 control.")
        sb.AppendLine("    '''</summary>")
        sb.AppendLine("    '''<remarks>")
        sb.AppendLine("    '''Auto-generated field.")
        sb.AppendLine("    '''To modify move field declaration from designer file to code-behind file.")
        sb.AppendLine("    '''</remarks>")
        sb.AppendLine("    Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm")
        sb.AppendLine()

        For Each Column As PCGColumn In TableGen.Columns
            If Column.IsDisplayColumn = True Then
                sb.AppendLine("    '''<summary>")
                sb.AppendLine("    '''" & Column.ControlName & " control.")
                sb.AppendLine("    '''</summary>")
                sb.AppendLine("    '''<remarks>")
                sb.AppendLine("    '''Auto-generated field.")
                sb.AppendLine("    '''To modify move field declaration from designer file to code-behind file.")
                sb.AppendLine("    '''</remarks>")
                sb.AppendLine("    Protected WithEvents " & Column.ControlName & " As " & Column.ControlType(TableGen.CodeType) & "")
                sb.AppendLine("")
            End If
        Next

        Dim cmdDelete As New ASPXButton(TableGen.CodeType, "Delete")
        sb.Append(cmdDelete.DesignerToString)

        sb.AppendLine("")

        Dim cmdSave As New ASPXButton(TableGen.CodeType, "Save")
        sb.Append(cmdSave.DesignerToString)

        sb.AppendLine("")

        Dim cmdCancel As New ASPXButton(TableGen.CodeType, "Cancel")
        sb.Append(cmdCancel.DesignerToString)

        sb.AppendLine("End Class")

        Return sb.ToString
    End Function

    Protected Shared Function GetMasterASPXDesignerVB(ByVal TableGen As RawCreateScript) As String
        Dim sb As New StringBuilder

        sb.AppendLine("'''<summary>")
        sb.AppendLine("'''" & TableGen.TableName & " class.")
        sb.AppendLine("'''</summary>")
        sb.AppendLine("'''<remarks>")
        sb.AppendLine("'''Auto-generated class.")
        sb.AppendLine("'''</remarks>")
        sb.AppendLine("Partial public class " & TableGen.TableName)
        sb.AppendLine()

        sb.AppendLine("    '''<summary>")
        sb.AppendLine("    '''form1 control.")
        sb.AppendLine("    '''</summary>")
        sb.AppendLine("    '''<remarks>")
        sb.AppendLine("    '''Auto-generated field.")
        sb.AppendLine("    '''To modify move field declaration from designer file to code-behind file.")
        sb.AppendLine("    '''</remarks>")
        sb.AppendLine("    Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm")
        sb.AppendLine()

        sb.AppendLine("    '''<summary>")
        sb.AppendLine("    '''grd control.")
        sb.AppendLine("    '''</summary>")
        sb.AppendLine("    '''<remarks>")
        sb.AppendLine("    '''Auto-generated field.")
        sb.AppendLine("    '''To modify move field declaration from designer file to code-behind file.")
        sb.AppendLine("    '''</remarks>")
        sb.AppendLine("    Protected WithEvents grd As Global.System.Web.UI.WebControls.GridView")
        sb.AppendLine("")

        Dim cmdAddNew As New ASPXButton(TableGen.CodeType, "AddNew")
        sb.Append(cmdAddNew.DesignerToString)

        sb.AppendLine("End Class")

        Return sb.ToString

        Exit Function
    End Function

    Public Shared Function GetDatabaseImportLine(ByVal TableGen As RawCreateScript) As String
        Dim Result As String = ""

        Return "System.Data.SqlClient"

        'Select Case TableGen.DatabaseType.ToUpper
        '    Case "SQLSERVER"
        '        Result = 
        '    Case "MYSQL"
        '        Result = "MySql.Data.MySqlClient"
        '    Case "ORACLE"
        '        Result = "Oracle.DataAccess.Client"
        '    Case "ODBC"
        '        Result = "System.Data.Odbc"
        '    Case "OLEDB"
        '        Result = "System.Data.OleDb"
        '    Case "NATIVE"
        '        Select Case TableGen.DBDatabaseType.ToUpper
        '            Case "SQLSERVER"
        '                Result = "System.Data.SqlClient"
        '            Case "MYSQL"
        '                Result = "MySql.Data.MySqlClient"
        '            Case "ORACLE"
        '                Result = "Oracle.DataAccess.Client"
        '        End Select
        '        ';TableGen.AccessMethod

        '    Case Else
        '        Result = ""
        'End Select
        Return Result
    End Function

    Public Shared Function GetDatabaseCommandClassName(ByVal TableGen As RawCreateScript) As String
        Return "SqlCommand"
        'Select Case TableGen.DatabaseType.ToUpper
        '    Case "SQLSERVER"
        '        GetDatabaseCommandClassName = "SqlCommand"
        '    Case "MYSQL"
        '        GetDatabaseCommandClassName = "MySqlCommand"
        '    Case "ORACLE"
        '        GetDatabaseCommandClassName = "OracleCommand"
        '    Case "ODBC"
        '        GetDatabaseCommandClassName = "OdbcCommand"
        '    Case "OLEDB"
        '        GetDatabaseCommandClassName = "OleDbCommand"
        '    Case "NATIVE"
        '        Select Case TableGen.DBDatabaseType.ToUpper
        '            Case "SQLSERVER"
        '                GetDatabaseCommandClassName = "SqlCommand"
        '            Case "MYSQL"
        '                GetDatabaseCommandClassName = "MySqlCommand"
        '            Case "ORACLE"
        '                GetDatabaseCommandClassName = "OracleCommand"
        '            Case Else
        '                GetDatabaseCommandClassName = ""
        '        End Select
        '    Case Else
        '        GetDatabaseCommandClassName = ""
        'End Select

    End Function

    Public Shared Function GetDatabaseConnectionClassName(ByVal TableGen As RawCreateScript) As String
        Return "SqlConnection"
        'GetDatabaseConnectionClassName = ""
        'Select Case TableGen.DatabaseType.ToUpper
        '    Case "SQLSERVER"
        '        GetDatabaseConnectionClassName = "SqlConnection"
        '    Case "MYSQL"
        '        GetDatabaseConnectionClassName = "MySqlConnection"
        '    Case "ORACLE"
        '        GetDatabaseConnectionClassName = "OracleConnection"
        '    Case "ODBC"
        '        GetDatabaseConnectionClassName = "OdbcConnection"
        '    Case "OLEDB"
        '        GetDatabaseConnectionClassName = "OleDbConnection"
        '    Case "NATIVE"
        '        Select Case TableGen.DBDatabaseType.ToUpper
        '            Case "SQLSERVER"
        '                GetDatabaseConnectionClassName = "SqlConnection"
        '            Case "MYSQL"
        '                GetDatabaseConnectionClassName = "MySqlConnection"
        '            Case "ORACLE"
        '                GetDatabaseConnectionClassName = "OracleConnection"
        '        End Select

        '    Case Else
        '        GetDatabaseConnectionClassName = ""
        'End Select
    End Function

    Public Shared Function GetDatabaseReaderClassName(ByVal TableGen As RawCreateScript) As String
        Return "SqlDataReader"
        'Dim Result As String = ""
        'Select Case TableGen.DatabaseType.ToUpper
        '    Case "SQLSERVER"
        '        Result = "SqlDataReader"
        '    Case "MYSQL"
        '        Result = "MySqlDataReader"
        '    Case "ORACLE"
        '        Result = "OracleDataReader"
        '    Case "ODBC"
        '        Result = "OdbcDataReader"
        '    Case "OLEDB"
        '        Result = "OleDbDataReader"
        '    Case "NATIVE"
        '        Select Case TableGen.DBDatabaseType.ToUpper
        '            Case "SQLSERVER"
        '                Result = "SqlDataReader"
        '            Case "MYSQL"
        '                Result = "MySqlDataReader"
        '            Case "ORACLE"
        '                Result = "OracleDataReader"
        '        End Select
        '    Case Else
        '        Result = ""
        'End Select
        'Return Result
    End Function

    Public Shared Function CommandParametersAddWithValue(ByVal TableGen As RawCreateScript) As String
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005, CodeTypeEnum.CS2005
                CommandParametersAddWithValue = "AddWithValue"
            Case Else
                CommandParametersAddWithValue = ""
        End Select
    End Function

    Public Shared Function GetAutonumberPassingField(ByVal tablegen As RawCreateScript) As String
        GetAutonumberPassingField = ""
        Select Case tablegen.EditKeyPassing
            Case EditKeyPassingEnum.Session
                Select Case tablegen.CodeType
                    Case CodeTypeEnum.VB2005
                        GetAutonumberPassingField = "Session(""Edit" & tablegen.TableName & "." & tablegen.AutoNumberColumn & """)"
                    Case CodeTypeEnum.CS2005
                        GetAutonumberPassingField = "SessionValue(""Edit" & tablegen.TableName & "." & tablegen.AutoNumberColumn & """)"
                End Select
            Case EditKeyPassingEnum.Inline
                GetAutonumberPassingField = "ID.Text"
            Case Else
                Select Case tablegen.CodeType
                    Case CodeTypeEnum.VB2005
                        GetAutonumberPassingField = "Request(""ID"")"
                    Case CodeTypeEnum.CS2005
                        GetAutonumberPassingField = "RequestValue(""ID"")"
                End Select
        End Select
    End Function

    Public Shared Function GetCS(ByVal ConnectionStringMethod As String, ByVal ConnectionString As String, Optional ByVal CodeType As CodeTypeEnum = CodeTypeEnum.VB2005) As String
        Dim c As New RawCreateScript()
        c.ConnectionString = ConnectionString
        c.ConnectionStringMethod = ConnectionStringMethod
        c.CodeType = CodeType
        Return GetCS(c)
    End Function

    Private Shared Function GetCS(ByVal TableGen As RawCreateScript) As String
        GetCS = ""
        Select Case TableGen.ConnectionStringMethod.ToUpper
            Case "GLOBAL CLASS VARIABLE"
                GetCS = TableGen.ConnectionString
            Case EditKeyPassingEnum.Session
                GetCS = TableGen.ConnectionString
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        GetCS = "Session(""" & TableGen.ConnectionString & """).ToString()"
                    Case CodeTypeEnum.CS2005
                        GetCS = "Session[""" & TableGen.ConnectionString & """].ToString()"
                End Select

            Case "APPLICATION"
                'GetCS = TableGen.ConnectionString
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        GetCS = "Application(""" & TableGen.ConnectionString & """).ToString()"
                    Case CodeTypeEnum.CS2005
                        GetCS = "Application[""" & TableGen.ConnectionString & """].ToString()"
                End Select

            Case "WEB.CONFIG CONNECTION STRINGS"
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        GetCS = "System.Configuration.ConfigurationManager.ConnectionStrings(""" & TableGen.ConnectionString & """).ConnectionString"
                    Case CodeTypeEnum.CS2005
                        GetCS = "System.Configuration.ConfigurationManager.ConnectionStrings[""" & TableGen.ConnectionString & """].ConnectionString"
                End Select
            Case "WEB.CONFIG APP SETTINGS"
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        GetCS = "System.Configuration.ConfigurationManager.AppSettings(""" & TableGen.ConnectionString & """)"
                    Case CodeTypeEnum.CS2005
                        GetCS = "System.Configuration.ConfigurationManager.AppSettings[""" & TableGen.ConnectionString & """]"
                End Select
            Case Else
                GetCS = ""
        End Select
    End Function

    Public Shared Function GetRequestValueFunction(ByVal TableGen As RawCreateScript) As String
        Dim sb As New StringBuilder
        Dim Spaces As New Space(1)
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                sb.AppendLine(Spaces.ToString() & "private string RequestValue(string Key)")
        End Select

        sb.AppendLine(Spaces.ToString() & "{")
        Spaces.Inc()
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                sb.AppendLine(Spaces.ToString() & "Object RequestObject = Request[Key];")
        End Select

        sb.AppendLine(Spaces.ToString() & "if ( RequestObject == null  ) ")
        sb.AppendLine(Spaces.ToString() & "{")
        Spaces.Inc()
        sb.AppendLine(Spaces.ToString() & "return """";")
        Spaces.Dec()
        GetElse(sb, Spaces, TableGen)
        Spaces.Inc()
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                sb.AppendLine(Spaces.ToString() & "return Request[Key].ToString();")
        End Select
        Spaces.Dec()
        sb.AppendLine(Spaces.ToString() & "}")
        Spaces.Dec()
        sb.AppendLine(Spaces.ToString() & "}")

        Return sb.ToString
    End Function

    Public Shared Function GetSessionValueFunction(ByVal TableGen As RawCreateScript) As String
        Dim sb As New StringBuilder
        sb.AppendLine()
        Dim Spaces As New Space(1)
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                sb.AppendLine(Spaces.ToString() & "private string SessionValue(string Key)")
            Case Else
                Return ""
        End Select

        sb.AppendLine(Spaces.ToString() & "{")
        Spaces.Inc()
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                sb.AppendLine(Spaces.ToString() & "Object SessionObject = Session[Key];")
        End Select

        sb.AppendLine(Spaces.ToString() & "if ( SessionObject == null  ) ")
        sb.AppendLine(Spaces.ToString() & "{")
        Spaces.Inc()
        sb.AppendLine(Spaces.ToString() & "return """";")
        Spaces.Dec()
        GetElse(sb, Spaces, TableGen)
        Spaces.Inc()
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                sb.AppendLine(Spaces.ToString() & "return Session[Key].ToString();")
        End Select
        Spaces.Dec()
        sb.AppendLine(Spaces.ToString() & "}")
        Spaces.Dec()
        sb.AppendLine(Spaces.ToString() & "}")

        Return sb.ToString
    End Function

    Public Shared Sub GetIsNumericFunction(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                sb.AppendLine()
                sb.AppendLine(spaces.ToString & "private bool IsNumeric(string TextNumber)")
                sb.AppendLine(spaces.ToString & "{")
                spaces.Inc()
                sb.AppendLine(spaces.ToString & "Regex RegexIsNumeric = new Regex(@""^(?:(?:[+\-]?\$?)|(?:\$?[+\-]?))?(?:(?:\d{1,3}(?:(?:,\d{3})|(?:\d))*(?:\.(?:\d*|\d+[eE][+\-]\d+))?)|(?:\.\d+(?:[eE][+\-]\d+)?))$"");")
                sb.AppendLine(spaces.ToString & "Match MatchIsNumeric = RegexIsNumeric.Match(TextNumber);")
                sb.AppendLine(spaces.ToString & "return MatchIsNumeric.Success;")
                spaces.Dec()
                sb.AppendLine(spaces.ToString & "} ")
        End Select
    End Sub

    Public Shared Sub GetIsDateFunction(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                sb.AppendLine()
                sb.AppendLine(spaces.ToString() & "private bool IsDate(String s)")
                sb.AppendLine(spaces.ToString() & "{")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "DateTime Result = new DateTime();")
                sb.AppendLine(spaces.ToString() & "return DateTime.TryParse(s, out Result);")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "}")

        End Select
    End Sub

    Public Shared Function DeclareAndOpenConnection(ByVal spaces As Space, ByVal TableGen As RawCreateScript) As String
        Dim sb As New StringBuilder
        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, "Create a new connection to the database")

            Case CommentLevelEnum.Verbose
                sb.AppendLine()

                AddComment(sb, TableGen, spaces, "Declare Connection Variable (Connection)")
                AddComment(sb, TableGen, spaces, "Create a new object " & GetDatabaseConnectionClassName(TableGen) & " with the connection string initialized")
                AddComment(sb, TableGen, spaces, "Set the Connection variable to point to the new object instance.")
                AddComment(sb, TableGen, spaces, "If connection goes out of scope the database connection won't be closed and must be closed with either ( Close or Disopose )")
        End Select
        sb.Append(DimVariableAsNewClassName(TableGen, spaces, "Connection", GetDatabaseConnectionClassName(TableGen), GetCS(TableGen)))

        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, "Opens a connection to the database.")

            Case CommentLevelEnum.Verbose
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, "Opens a connection to the database.")
                AddComment(sb, TableGen, spaces, "If available draws from an open conneciton from the connection pool(if available)")
        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Connection.Open()")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Connection.Open();")
        End Select
        Return sb.ToString
    End Function

    Public Shared Function RequestField(ByVal RequestFieldName As String, ByVal TableGen As RawCreateScript) As String
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                RequestField = "Request(""" & RequestFieldName & """)"
            Case CodeTypeEnum.CS2005
                RequestField = "RequestValue(""" & RequestFieldName & """)"
            Case Else
                Throw New Exception("RequestField syclical failure")
        End Select
    End Function

    Public Shared Function SetSessionField(ByVal SessionFieldName As String, ByVal TableGen As RawCreateScript) As String
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                SetSessionField = "Session(""" & SessionFieldName & """)"
            Case CodeTypeEnum.CS2005
                SetSessionField = "Session[""" & SessionFieldName & """]"
            Case Else
                Throw New Exception("SessionField field syclical failure")
        End Select
    End Function

    Public Shared Function ReadSessionField(ByVal SessionFieldName As String, ByVal TableGen As RawCreateScript) As String
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                ReadSessionField = "Session(""" & SessionFieldName & """)"
            Case CodeTypeEnum.CS2005
                ReadSessionField = "SessionValue(""" & SessionFieldName & """)"
            Case Else
                Throw New Exception("SessionField field syclical failure")
        End Select
    End Function

    Public Shared Function CaseStatement(ByVal Key As String, ByVal Tablegen As RawCreateScript) As String
        Select Case Tablegen.CodeType
            Case CodeTypeEnum.VB2005
                Return "Case """ & Key & """"
            Case CodeTypeEnum.CS2005
                Return "case """ & Key & """:"
            Case Else
                Return ""
        End Select
    End Function

    Public Shared Function CaseElse(ByVal Tablegen As RawCreateScript) As String
        Select Case Tablegen.CodeType
            Case CodeTypeEnum.VB2005
                Return "Case else"
            Case CodeTypeEnum.CS2005
                Return "default:"
            Case Else
                Return ""
        End Select
    End Function

    Public Shared Function EndSelect(ByVal Tablegen As RawCreateScript) As String
        Select Case Tablegen.CodeType
            Case CodeTypeEnum.VB2005
                Return "End Select"
            Case CodeTypeEnum.CS2005
                Return "}"
            Case Else
                Return ""
        End Select
    End Function

    Public Shared Sub EndCaseSection(ByVal sb As StringBuilder, ByVal s As Space, ByVal tablegen As RawCreateScript)
        Select Case tablegen.CodeType
            Case CodeTypeEnum.VB2005
            Case CodeTypeEnum.CS2005
                sb.AppendLine(s.ToString() & "break;")
            Case Else

        End Select
    End Sub

    Public Shared Function EditVBReturnToMaster(ByVal TableGen As RawCreateScript) As String
        EditVBReturnToMaster = ""

        EditVBReturnToMaster = "        Response.Redirect(""" & TableGen.OutputFileName & ".aspx"")" & EndStatement(TableGen) & vbCrLf

    End Function

    Public Shared Function CommandParameter(ByVal AtKey As String, ByVal Value As String, ByVal tablegen As RawCreateScript) As String
        CommandParameter = ""
        Select Case tablegen.CodeType
            Case CodeTypeEnum.VB2005
                CommandParameter = "            Command.Parameters." & CommandParametersAddWithValue(tablegen) & "(""@" & AtKey & """, " & Value & ")" & vbCrLf
            Case CodeTypeEnum.CS2005
                CommandParameter = "            Command.Parameters." & CommandParametersAddWithValue(tablegen) & "(""@" & AtKey & """, " & Value & ");" & vbCrLf
        End Select
    End Function


    Public Shared Sub GetEndSub(ByVal sb As StringBuilder, ByVal Spaces As Space, ByVal TableGen As RawCreateScript)

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(Spaces.ToString & "End Sub")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(Spaces.ToString & "}")
        End Select

    End Sub


    Public Shared Sub GetEndFunction(ByVal sb As StringBuilder, ByVal spaces As Space, ByVal TableGen As RawCreateScript)
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "End Function")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "}")
        End Select
    End Sub

    Public Shared Sub GetEndIf(ByVal sb As StringBuilder, ByVal spaces As Space, ByVal TableGen As RawCreateScript, Optional ByVal Comment As String = "")

        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, Comment)
            Case CommentLevelEnum.Verbose
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, Comment)
        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "End If")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "}")
        End Select
    End Sub

    Public Shared Sub GetReturn(ByVal sb As StringBuilder, ByVal spaces As Space, ByVal TableGen As RawCreateScript, ByVal VariableName As String, Optional ByVal Comment As String = "")

        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, Comment)
            Case CommentLevelEnum.Verbose
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, Comment)
        End Select
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "Return " & VariableName)
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "return " & VariableName & EndStatement(TableGen))
        End Select
    End Sub

    Public Shared Sub GetElse(ByVal sb As StringBuilder, ByVal space As Space, ByVal TableGen As RawCreateScript)
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(space.ToString & "else")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(space.ToString & "} else {")
        End Select
    End Sub

    Public Shared Function EndStatement(ByVal TableGen As RawCreateScript) As String
        EndStatement = ""
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                EndStatement = ""
            Case CodeTypeEnum.CS2005
                EndStatement = ";"
        End Select
    End Function


    Public Shared Function EndStatement(ByVal CodeType As CodeTypeEnum) As String
        EndStatement = ""
        Select Case CodeType
            Case CodeTypeEnum.VB2005
                EndStatement = ""
            Case CodeTypeEnum.CS2005
                EndStatement = ";"
        End Select
    End Function

    Public Shared Function IfGreaterThan(ByVal LeftSide As String, ByVal rightside As String, ByVal TableGen As RawCreateScript) As String
        IfGreaterThan = ""
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                IfGreaterThan = "if " & LeftSide & " > " & rightside & "  Then"
            Case CodeTypeEnum.CS2005
                IfGreaterThan = "if (" & LeftSide & " > " & rightside & ") {"
        End Select

    End Function

    Public Shared Function GetElseIfEquals(ByVal LeftSide As String, ByVal rightside As String, ByVal TableGen As RawCreateScript) As String
        GetElseIfEquals = ""
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                GetElseIfEquals = "elseif " & LeftSide & " = " & rightside & " Then"
            Case CodeTypeEnum.CS2005
                GetElseIfEquals = "} else if (" & LeftSide & " == " & rightside & ") {"
        End Select
    End Function

    Public Shared Function IfEquals(ByVal LeftSide As String, ByVal rightside As String, ByVal TableGen As RawCreateScript) As String
        IfEquals = ""
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                IfEquals = "if " & LeftSide & " = " & rightside & " Then"
            Case CodeTypeEnum.CS2005
                IfEquals = "if (" & LeftSide & " == " & rightside & ") {"
        End Select

    End Function

    Public Shared Sub GetIfEquals(ByVal LeftSide As String, ByVal rightside As String, ByVal TableGen As RawCreateScript, ByVal Spaces As Space, ByVal sb As StringBuilder)
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(Spaces.ToString & "if " & LeftSide & " = " & rightside & " Then")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(Spaces.ToString & "if (" & LeftSide & " == " & rightside & ") {")
        End Select
    End Sub

    Public Shared Function OperatorConcatenate(ByVal TableGen As RawCreateScript) As String
        OperatorConcatenate = ""
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                OperatorConcatenate = "&"
            Case CodeTypeEnum.CS2005
                OperatorConcatenate = "+"
        End Select
    End Function

    Public Shared Function OperatorStringIndex(ByVal TableGen As RawCreateScript, ByVal StringKeyName As String) As String
        Select Case TableGen.CodeType

            Case CodeTypeEnum.CS2005
                Return "[""" & StringKeyName & """]"
            Case CodeTypeEnum.VB2005
                Return "(""" & StringKeyName & """)"
            Case Else
                Return "(""" & StringKeyName & """)"
        End Select
    End Function

    Public Shared Function OperatorNumericIndex(ByVal TableGen As RawCreateScript, ByVal NumericIn As String) As String
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                Return "[" & NumericIn & "]"
            Case CodeTypeEnum.VB2005
                Return "(" & NumericIn & ")"
            Case Else
                Return "(" & NumericIn & ")"
        End Select
    End Function

    Public Shared Function GetCommandObjectWithConstructor(ByVal TableGen As RawCreateScript, ByVal Spaces As Space, Optional ByVal CommandName As String = "Command", Optional ByVal SQLName As String = "sql", Optional ByVal SQLConnection As String = "Connection") As String
        GetCommandObjectWithConstructor = ""
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                GetCommandObjectWithConstructor = Spaces.ToString() & "Dim " & CommandName & " As New " & GetDatabaseCommandClassName(TableGen) & "(" & SQLName & ", " & SQLConnection & ")"
            Case CodeTypeEnum.CS2005
                GetCommandObjectWithConstructor = Spaces.ToString() & GetDatabaseCommandClassName(TableGen) & " " & CommandName & " = new " & GetDatabaseCommandClassName(TableGen) & "(" & SQLName & ", " & SQLConnection & ")" & EndStatement(TableGen)
        End Select

    End Function


    Public Shared Function GetStringIndex(ByVal TableGen As RawCreateScript, ByVal KeyName As String) As String
        GetStringIndex = ""
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                GetStringIndex = "(""" & KeyName & """)"
            Case CodeTypeEnum.CS2005
                GetStringIndex = "[""" & KeyName & """]"
        End Select

    End Function

    Public Shared Function DimVariableAsClassName(ByVal TableGen As RawCreateScript, ByVal Spaces As Space, ByVal VariableName As String, ByVal ClassName As String, Optional ByVal DefaultValue As String = "") As String

        DimVariableAsClassName = Spaces.ToString
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                If Len(DefaultValue) > 0 Then
                    DimVariableAsClassName = DimVariableAsClassName & "Dim " & VariableName & " as " & ClassName & " = " & DefaultValue
                Else
                    DimVariableAsClassName = DimVariableAsClassName & "Dim " & VariableName & " as new " & ClassName & "()"
                End If
            Case CodeTypeEnum.CS2005
                If Len(DefaultValue) > 0 Then
                    DimVariableAsClassName = DimVariableAsClassName & ClassName & " " & VariableName & " = " & DefaultValue
                Else
                    DimVariableAsClassName = DimVariableAsClassName & ClassName & " " & VariableName & " = new " & ClassName
                End If
        End Select

    End Function

    Public Shared Function GetTrue(ByVal Tablegen As RawCreateScript) As String
        Select Case Tablegen.CodeType
            Case CodeTypeEnum.VB2005
                Return "True"
            Case CodeTypeEnum.CS2005
                Return "true"
            Case Else
                Return ""
        End Select
    End Function

    Public Shared Function GetFalse(ByVal Tablegen As RawCreateScript) As String
        Select Case Tablegen.CodeType
            Case CodeTypeEnum.VB2005
                Return "False"
            Case CodeTypeEnum.CS2005
                Return "false"
            Case Else
                Return ""
        End Select
    End Function

    Public Shared Function PrivateVariableAsClassName(ByVal TableGen As RawCreateScript, ByVal Spaces As Space, ByVal VariableName As String, ByVal ClassName As String, Optional ByVal DefaultValue As String = "") As String

        PrivateVariableAsClassName = Spaces.ToString
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                If Len(DefaultValue) > 0 Then
                    PrivateVariableAsClassName = PrivateVariableAsClassName & "Private " & VariableName & " as " & ClassName & " = " & DefaultValue
                Else
                    PrivateVariableAsClassName = PrivateVariableAsClassName & "Private " & VariableName & " as new " & ClassName & "()"
                End If
            Case CodeTypeEnum.CS2005
                If Len(DefaultValue) > 0 Then
                    PrivateVariableAsClassName = PrivateVariableAsClassName & ClassName & " " & VariableName & " = " & DefaultValue & EndStatement(TableGen)
                Else
                    PrivateVariableAsClassName = PrivateVariableAsClassName & ClassName & " " & VariableName & " = new " & ClassName & EndStatement(TableGen)
                End If
        End Select

    End Function

    Public Shared Function DimVariableAsNewClassName(ByVal TableGen As RawCreateScript, ByVal spaces As Space, ByVal VariableName As String, ByVal ClassName As String, Optional ByVal DefaultList As String = "") As String
        DimVariableAsNewClassName = ""

        'Select Case TableGen.CommentLevel
        '    Case 0
        '        DimVariableAsNewClassName = DimVariableAsNewClassName & spaces.ToString & "'Declare " & GetDatabaseConnectionClassName(TableGen) & " Object" & vbCrLf
        '    Case 1
        '        DimVariableAsNewClassName = DimVariableAsNewClassName & spaces.ToString & "'Declare " & GetDatabaseConnectionClassName(TableGen) & " Object named Connection" & vbCrLf
        '        DimVariableAsNewClassName = DimVariableAsNewClassName & spaces.ToString & "'Set the Connection to a new instance of " & GetDatabaseConnectionClassName(TableGen) & "" & vbCrLf
        '    Case 2
        '        DimVariableAsNewClassName = DimVariableAsNewClassName & spaces.ToString & "'Declare " & GetDatabaseConnectionClassName(TableGen) & " Object named Connection" & vbCrLf
        '        DimVariableAsNewClassName = DimVariableAsNewClassName & spaces.ToString & "'Set the Connection to a new instance of " & GetDatabaseConnectionClassName(TableGen) & "" & vbCrLf
        'End Select

        DimVariableAsNewClassName = spaces.ToString
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                DimVariableAsNewClassName = DimVariableAsNewClassName & "Dim " & VariableName & " as new " & ClassName
            Case CodeTypeEnum.CS2005
                DimVariableAsNewClassName = DimVariableAsNewClassName & ClassName & " " & VariableName & " = new " & ClassName
        End Select
        If Len(DefaultList) > 0 Then
            DimVariableAsNewClassName = DimVariableAsNewClassName & "(" & DefaultList & ")"
        Else
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005

                Case CodeTypeEnum.CS2005
                    DimVariableAsNewClassName = DimVariableAsNewClassName & "()"
            End Select
        End If
        DimVariableAsNewClassName = DimVariableAsNewClassName & EndStatement(TableGen)

        DimVariableAsNewClassName = DimVariableAsNewClassName & vbCrLf
    End Function

    Public Shared Function GetIsPostbackEqualFalse(ByVal spaces As Space, ByVal TableGen As RawCreateScript) As String
        Dim sb As New StringBuilder
        GetIsPostbackEqualFalse = ""


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, "Evaluates to true when the page is loaded for the first time.")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, "When True: The page is loaded for the first time")
                AddComment(sb, TableGen, spaces, "When False: More than likely a button was clicked or user action has happened, after the page was loaded.")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "If IsPostBack = False Then")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "if (IsPostBack == false)")
                sb.AppendLine(spaces.ToString & "{")
        End Select
        Return sb.ToString
    End Function

    Public Shared Sub AddComment(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space, ByVal Comment As String)

        If Comment.Length = 0 Then
            Exit Sub
        End If
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "'" & Comment)
                'AddComment = AddComment() & Spaces.ToString & "'" & Comment & vbCrLf
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "//" & Comment)
                'AddComment = AddComment() & Spaces.ToString & "//" & Comment & vbCrLf
        End Select
    End Sub

    Public Shared Function GetPCGStyleSheetDotCSS() As String
        Dim Stylesheet As New StyleSheet
        Return Stylesheet.ToString
    End Function


    Public Shared Function GetPCGDataContext(ByVal DatabaseName As String, ByVal TableGen As RawCreateScript) As String
        Dim Result As String = ""
        Result = GetDataContextDBMLHeader(DatabaseName)
        Return Result
    End Function

    Public Shared Function GetDataContextDBMLHeader(ByVal DatabaseName As String) As String
        Dim output As String = ""
        output = output & "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf
        output = output & "<Database Name=""" & DatabaseName & """ Class=""PCGDataContext"" xmlns=""http://schemas.microsoft.com/linqtosql/dbml/2007"">" & vbCrLf
        Return output
    End Function

    Public Shared Function GetDataContextDBMLFooter() As String
        Dim output As String = ""
        output = output & "</Database>" & vbCrLf
        Return output
    End Function

    Public Shared Function GetDataContextDBML(ByVal TableGen As RawCreateScript) As String
        Dim sb As New StringBuilder
        sb.AppendLine("<Table Name=""[" & TableGen.TableName & "]"" Member=""" & TableGen.SafeTableName & "s"">")
        sb.AppendLine(" <Type Name=""" & TableGen.TableName & """>")
        For Each Column As PCGColumn In TableGen.Columns
            sb.Append(" <Column Name=""[" & Column.ColumnName & "]"" ")
            sb.Append("Member=""" & Column.SafeParameterName() & """ ")
            sb.Append("Type=""" & Column.DBMLDataType & """ ")
            sb.Append("DbType=""" & Column.DBMLDataDBType & """ ")
            If Column.IsDbGenerated Then
                sb.Append("IsDbGenerated=""true"" ")
            Else
                'do nothing
            End If
            If Column.AllowNulls Then
                sb.Append("CanBeNull=""true""")
            Else
                sb.Append("CanBeNull=""false""")
            End If
            sb.AppendLine(" />")
        Next

        sb.AppendLine(" </Type>")

        sb.AppendLine("</Table>")
        Return sb.ToString
    End Function

    Public Shared Sub DoWhileReaderDotRead(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[DoWhileReaderDotRead]")
        End If

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Do While Reader.Read()")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "while (Reader.Read()) ")
                sb.AppendLine(spaces.ToString & "{")
        End Select
    End Sub


    Public Shared Sub GetPageLoad(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetPageLoad]")
        End If


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, "The Page_Load function is called every time the page is reloaded.")
                AddComment(sb, TableGen, spaces, "If a button is clicked Page_Load is called first, then the button event handler.")
        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "protected void Page_Load(object sender, EventArgs e)")
                sb.AppendLine(spaces.ToString & "{")
        End Select
    End Sub

    Public Shared Sub DimReaderAsSQLDataReaderEqualsCommandDotExecuteReader(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[DimReaderAsSQLDataReaderEqualsCommandDotExecuteReader]")
        End If

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Dim Reader As " & GetDatabaseReaderClassName(TableGen) & " = Command.ExecuteReader")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & GetDatabaseReaderClassName(TableGen) & " Reader = Command.ExecuteReader();")
        End Select
    End Sub

    Public Shared Sub ReaderDotClose(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[ReaderDotClose]")
        End If


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Close the Data Reader we are done with it.")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Close the Data Reader we are done with it.")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Reader.Close()")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Reader.Close();")
        End Select

    End Sub

    Public Shared Sub ConnectionDotClose(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[ConnectionDotClose]")
        End If

        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, "Close the Connection Object ")

            Case CommentLevelEnum.Verbose
                sb.AppendLine()
                AddComment(sb, TableGen, spaces, "Closes the Connection to the back to the connection pool.")
        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Connection.Close()")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Connection.Close();")
        End Select

    End Sub

    Public Shared Sub VBLoop(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[VBLoop]")
        End If

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Loop")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "}")
        End Select
    End Sub

    Public Shared Sub CommandEqualsNewSqlCommandPassSQLCommaConnection(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space, ByVal SQLVariableName As String)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[CommandEqualsNewSqlCommandPassSQLCommaConnection]")
        End If

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Command = New " & GetDatabaseCommandClassName(TableGen) & "(" & SQLVariableName & ", Connection)")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Command = New " & GetDatabaseCommandClassName(TableGen) & "(" & SQLVariableName & ", Connection);")
        End Select
    End Sub

    Public Shared Sub DimCommandAsNewSqlCommandPassSQLCommaConnection(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space, ByVal SQLVariableName As String)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[DimCommandAsNewSqlCommandPassSQLCommaConnection]")
        End If

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Dim Command as New " & GetDatabaseCommandClassName(TableGen) & "(" & SQLVariableName & ", Connection)")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Dim Command as New " & GetDatabaseCommandClassName(TableGen) & "(" & SQLVariableName & ", Connection);")
        End Select
    End Sub

    Public Shared Sub CommandDotExecuteNonQuery(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal spaces As Space)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[CommandDotExecuteNonQuery]")
        End If

        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Run the statement")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Run the statement ExecuteNonQuery returns no Results.")

        End Select
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Command.ExecuteNonQuery()")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Command.ExecuteNonQuery();")
        End Select
    End Sub

    Public Shared Sub GetIfLengthGreaterThanZero(ByVal RenderedFields As String, ByVal sb As StringBuilder, ByVal spaces As Space, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetIfLengthGreaterThanZero]")
        End If

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "If Len(" & RenderedFields & ") > 0 Then")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "if (" & RenderedFields & ".ToString().Length > 0 )")
                sb.AppendLine(spaces.ToString & "{")
        End Select

    End Sub

    Public Shared Sub GetIfLengthEqualToZero(ByVal RenderedFields As String, ByVal sb As StringBuilder, ByVal spaces As Space, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetIfLengthEqualToZero]")
        End If

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "If Len(" & RenderedFields & ") = 0 Then")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "if (" & RenderedFields & ".ToString().Length == 0 )")
                sb.AppendLine(spaces.ToString & "{")
        End Select
    End Sub

    Public Shared Sub GetIfCountEqualToValue(ByVal RenderedFields As String, ByVal Value As String, ByVal sb As StringBuilder, ByVal spaces As Space, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetIfCountEqualToValue]")
        End If

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "If " & RenderedFields & ".Count = " & Value & " Then")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "if (" & RenderedFields & ".Count == " & Value & " )")
                sb.AppendLine(spaces.ToString & "{")
        End Select
    End Sub

    Public Shared Sub GetIfReaderDotRead(ByVal sb As StringBuilder, ByVal spaces As Space, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetIfReaderDotRead]")
        End If
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "If Reader.Read Then")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "if ( Reader.Read() ) ")
                sb.AppendLine(spaces.ToString & "{ ")
        End Select
        spaces.Inc()

    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub

    Public Shared Function SQLDataTypeToGenType(ByVal SQLDataType As String, Optional ByVal CodeType As CodeTypeEnum = CodeTypeEnum.VB2005) As String
        Select Case SQLDataType.ToUpper
            Case "INT", "AUTONUMBER", "BIGINT", "TINYINT", "SMALLINT"
                Select Case CodeType
                    Case CodeTypeEnum.VB2005
                        Return "Long"
                    Case Else
                        Return "long"
                End Select
            Case "VARCHAR", "NVARCHAR"
                Return "String"
            Case "DATETIME"
                Return "DateTime"
            Case "BIT"
                Return "Boolean"
            Case "NTEXT", "TEXT"
                Return "String"
            Case "NCHAR", "CHAR"
                Return "String"
            Case "MONEY", "FLOAT", "DECIMAL", "NUMERIC"
                Select Case CodeType
                    Case CodeTypeEnum.VB2005
                        Return "Double"
                    Case Else
                        Return "double"
                End Select

            Case "UNIQUEIDENTIFIER"
                Return "Guid"
            Case Else
                Debug.WriteLine("Support.SQLDataTypeToGenType unhandled: " & SQLDataType)
                Return "String"
        End Select
        Return ""
    End Function

    Public Shared Sub GetFirstAtLineASPX(ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        Dim Extension As String = ""
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                Extension = "vb"
            Case CodeTypeEnum.CS2005
                Extension = "cs"
        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.Append("<%@ Page Language=""vb"" ")
            Case CodeTypeEnum.CS2005
                sb.Append("<%@ Page Language=""C#"" ")
        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.Append(" AutoEventWireup=""false"" CodeFile=""")
                sb.Append(TableGen.OutputFileName)
                sb.Append(".aspx.")
                sb.Append(Extension)
                sb.Append(""" Inherits=""")
                sb.Append(TableGen.ClassName)
                sb.AppendLine("""%>")
            Case CodeTypeEnum.CS2005
                sb.Append(" AutoEventWireup=""true"" CodeFile=""")
                sb.Append(TableGen.OutputFileName)
                sb.Append(".aspx.")
                sb.Append(Extension)
                sb.Append(""" Inherits=""")
                sb.Append(TableGen.ClassName)
                sb.AppendLine(""" %>")
        End Select

    End Sub

    Public Shared Function GetConnectionStringFromTreeNode(ByVal TreeNode As TreeNode) As String
        Dim CurrentNode As TreeNode = TreeNode
        Do While CurrentNode Is Nothing = False
            Dim DatabaseObject As DatabaseObject = CurrentNode.Tag
            If DatabaseObject.Type = DatabaseObjectType.Server Then
                Dim DatabaseServer As DatabaseServer = DatabaseObject
                Return DatabaseServer.ConnectionString
            Else
                'do nothing
            End If
            CurrentNode = CurrentNode.Parent
        Loop
        Return ""
    End Function


    Public Shared Function GetDatabaseServerFromTreeNode(ByVal TreeNode As TreeNode) As DatabaseServer
        GetDatabaseServerFromTreeNode = Nothing
        Dim CurrentNode As TreeNode = TreeNode
        Do While CurrentNode Is Nothing = False
            Dim DatabaseObject As DatabaseObject = CurrentNode.Tag
            If DatabaseObject.Type = DatabaseObjectType.Server Then
                Return DatabaseObject
                'Dim DatabaseServer As DatabaseServer = DatabaseObject
                'Return DatabaseServer.ConnectionString
            Else
                'do nothing
            End If
            CurrentNode = CurrentNode.Parent
        Loop
        'Return ""
    End Function

    Public Shared Sub JQueryDateSection(ByVal sb As StringBuilder, ByVal ControlName As String, ByVal Spaces As Space)

        sb.AppendLine(Spaces.ToString() & "$('#" & ControlName & "').datepicker({")
        Spaces.Inc()
        sb.AppendLine(Spaces.ToString() & "numberOfMonths: 1,")
        sb.AppendLine(Spaces.ToString() & "showButtonPanel: true,")
        sb.AppendLine(Spaces.ToString() & "showOn: 'both', ")
        sb.AppendLine(Spaces.ToString() & "buttonImage: 'calendar.gif',")
        sb.AppendLine(Spaces.ToString() & "buttonImageOnly: false,")
        sb.AppendLine(Spaces.ToString() & "changeYear: true,")
        sb.AppendLine(Spaces.ToString() & "beforeShow: function() { $('#ui-datepicker-div').css(""z-index"", 999999); }")
        sb.AppendLine(Spaces.ToString() & "//              ,changeMonth: true")
        Spaces.Dec()
        sb.AppendLine(Spaces.ToString() & "});")
    End Sub


    Public Shared Sub JQueryDateTimeSection(ByVal sb As StringBuilder, ByVal ControlName As String, ByVal Spaces As Space)

        sb.AppendLine(Spaces.ToString() & "$('#" & ControlName & "').datetimepicker({")
        Spaces.Inc()
        sb.AppendLine(Spaces.ToString() & "numberOfMonths: 1,")
        sb.AppendLine(Spaces.ToString() & "showButtonPanel: true,")
        sb.AppendLine(Spaces.ToString() & "showOn: 'both', ")
        sb.AppendLine(Spaces.ToString() & "buttonImage: 'calendar.gif',")
        sb.AppendLine(Spaces.ToString() & "buttonImageOnly: false,")
        sb.AppendLine(Spaces.ToString() & "changeYear: true,")
        sb.AppendLine(Spaces.ToString() & "beforeShow: function() { $('#ui-datepicker-div').css(""z-index"", 999999); }")
        sb.AppendLine(Spaces.ToString() & "//              ,changeMonth: true")
        Spaces.Dec()
        sb.AppendLine(Spaces.ToString() & "});")
    End Sub

    Public Shared Sub LoadThemesFunction(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal IsMaster As Boolean)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[LoadThemesFunction]")
        End If
        sb.AppendLine(spaces.ToString() & "")
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "Private Sub LoadThemes()")

            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "private void LoadThemes()")
                sb.AppendLine(spaces.ToString() & "{")

        End Select
        spaces.Inc()
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "Dim ThemeName As String = ""base""")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "String ThemeName = ""base"";")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "If IsNothing(Request.Cookies(""PCGSettings"")) = False Then")

            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "if ( Request.Cookies[""PCGSettings""] != null ) ")
                sb.AppendLine(spaces.ToString() & "{")
        End Select

        spaces.Inc()
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "If IsNothing(Request.Cookies(""PCGSettings"")(""Themes"")) = False Then")

            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "if ( Request.Cookies[""PCGSettings""][""Themes""] != null ) ")
                sb.AppendLine(spaces.ToString() & "{")

        End Select

        spaces.Inc()
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "ThemeName = Request.Cookies(""PCGSettings"")(""Themes"")")

            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "ThemeName = Request.Cookies[""PCGSettings""][""Themes""];")

        End Select
        If IsMaster Then
            sb.AppendLine(spaces.ToString() & "cboTheme.SelectedValue = ThemeName" & EndStatement(TableGen))
        End If


        spaces.Dec()
        GetEndIf(sb, spaces, TableGen)
        spaces.Dec()
        GetEndIf(sb, spaces, TableGen)
        sb.AppendLine(spaces.ToString() & "")
        sb.AppendLine(spaces.ToString() & "ThemesCSS.Attributes.Add(""href"", ""http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/"" " & OperatorConcatenate(TableGen) & " ThemeName " & OperatorConcatenate(TableGen) & " ""/ui.all.css"")" & EndStatement(TableGen))
        spaces.Dec()
        GetEndSub(sb, spaces, TableGen)
    End Sub

    Public Shared Sub SaveThemesCookieFunction(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[SaveThemesCookieFunction]")
        End If

        sb.AppendLine(spaces.ToString() & "")
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "Private Sub SaveThemesCookie(ByVal ThemeName As String)")

            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "private void SaveThemesCookie(String ThemeName)")
                sb.AppendLine(spaces.ToString() & "{")

        End Select

        spaces.Inc()
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "Dim Cookie As New HttpCookie(""PCGSettings"")")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "HttpCookie Cookie = new HttpCookie(""PCGSettings"");")
        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "Cookie(""Themes"") = ThemeName" & EndStatement(TableGen))

            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "Cookie[""Themes""] = ThemeName" & EndStatement(TableGen))

        End Select
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "Cookie.Expires = Now.AddYears(1)")

            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "Cookie.Expires = DateTime.Now.AddYears(1);")

        End Select

        sb.AppendLine(spaces.ToString() & "Response.Cookies.Add(Cookie)" & EndStatement(TableGen))
        spaces.Dec()
        GetEndSub(sb, spaces, TableGen)

    End Sub

    Public Shared Function GenerateReader(ByVal TableGen As RawCreateScript, ByVal ParameterName As String) As String
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                Return "Reader(""" & ParameterName & """)"
            Case CodeTypeEnum.CS2005
                Return "Reader[""" & ParameterName & """]"
        End Select
        Return ""
    End Function

    Public Shared Sub GetPageCountFunction(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetPageCountFunction]")
        End If

        Select Case TableGen.Paging
            Case PagingEnum.HighSpeed
                sb.AppendLine()
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & "Private Function GetPageCount() As Long")
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & "private decimal GetPageCount()")
                        sb.AppendLine(spaces.ToString & "{")
                End Select
                spaces.Inc()
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & "Dim WholePageCount As Long = Math.Floor(Session(""" & TableGen.SafeTableName & ".RecordsFound"") / PageSize)")
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & "decimal WholePageCount = Math.Floor(decimal.Parse(" & Support.ReadSessionField(TableGen.SafeTableName & ".RecordsFound", TableGen) & ") / PageSize);")
                End Select
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & "Dim PartialRecordCount As Long = Session(""" & TableGen.SafeTableName & ".RecordsFound"") Mod PageSize")
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & "decimal PartialRecordCount = decimal.Parse(" & Support.ReadSessionField(TableGen.SafeTableName & ".RecordsFound", TableGen) & ") % PageSize;")
                End Select
                sb.AppendLine(spaces.ToString & IfGreaterThan("PartialRecordCount", "0", TableGen))
                spaces.Inc()
                sb.AppendLine(spaces.ToString & "WholePageCount = WholePageCount + 1" & EndStatement(TableGen))
                spaces.Dec()
                GetEndIf(sb, spaces, TableGen)


                sb.AppendLine(spaces.ToString & IfEquals("WholePageCount", "0", TableGen))
                spaces.Inc()
                sb.AppendLine(spaces.ToString & "WholePageCount = 1" & EndStatement(TableGen))
                spaces.Dec()
                GetEndIf(sb, spaces, TableGen)

                sb.AppendLine()
                GetReturn(sb, spaces, TableGen, "WholePageCount")
                spaces.Dec()
                GetEndFunction(sb, spaces, TableGen)
        End Select

    End Sub

    Public Shared Sub cboThemeSelectedIndexChangedFunction(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "cboThemeSelectedIndexChangedFunction")
        End If
        sb.AppendLine()

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "Protected Sub cboTheme_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboTheme.SelectedIndexChanged")

            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "protected void cboTheme_SelectedIndexChanged(object sender, EventArgs e)")
                sb.AppendLine(spaces.ToString() & "{")

        End Select
        spaces.Inc()
        sb.AppendLine(spaces.ToString() & "ThemesCSS.Attributes.Add(""href"", ""http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/"" " & OperatorConcatenate(TableGen) & " cboTheme.SelectedValue " & OperatorConcatenate(TableGen) & " ""/ui.all.css"")" & EndStatement(TableGen))
        sb.AppendLine(spaces.ToString() & "SaveThemesCookie(cboTheme.SelectedValue)" & EndStatement(TableGen))
        sb.AppendLine(spaces.ToString() & "BindGrid()" & EndStatement(TableGen))
        spaces.Dec()
        GetEndSub(sb, spaces, TableGen)
    End Sub

    Public Shared Sub grdItemCreatedFunction(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "grdItemCreatedFunction")
        End If
        Select Case TableGen.Paging
            Case PagingEnum.HighSpeed
                Select Case TableGen.ViewType
                    Case ViewTypeEnum.Repeater

                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & "Protected Sub grd_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles grd.ItemCreated")

                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & "protected void grd_ItemCreated(object sender, RepeaterItemEventArgs e)")
                                sb.AppendLine(spaces.ToString & "{")
                        End Select

                        spaces.Inc()
                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & "If e.Item.ItemType = ListItemType.Item Then")
                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & "if ( e.Item.ItemType == ListItemType.Item )")
                                sb.AppendLine(spaces.ToString & "{")
                        End Select

                        spaces.Inc()
                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & "If IsNothing(grd.DataSource) = False Then")
                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & "if ( grd.DataSource != null ) ")
                                sb.AppendLine(spaces.ToString & "{")
                        End Select

                        spaces.Inc()
                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & "If IsDBNull(grd.DataSource(""RecordSetCount"")) = False Then")
                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & "SqlDataReader DataReader = (SqlDataReader)grd.DataSource;")
                                sb.AppendLine(spaces.ToString & "if ( DataReader[""RecordSetCount""] != null )")
                                sb.AppendLine(spaces.ToString & "{")
                        End Select

                        spaces.Inc()
                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".RecordsFound", TableGen) & " = grd.DataSource(""RecordSetCount"")" & EndStatement(TableGen))

                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".RecordsFound", TableGen) & " = DataReader[""RecordSetCount""]" & EndStatement(TableGen))

                        End Select
                        sb.AppendLine(spaces.ToString & "UpdateLabels()" & EndStatement(TableGen))
                        spaces.Dec()
                        GetEndIf(sb, spaces, TableGen)
                        spaces.Dec()
                        GetEndIf(sb, spaces, TableGen)
                        spaces.Dec()
                        GetEndIf(sb, spaces, TableGen)
                        spaces.Dec()
                        GetEndSub(sb, spaces, TableGen)
                End Select
        End Select
    End Sub

    Public Shared Sub HTMLCboTheme(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        Select Case TableGen.DevelopmentMode
            Case DevelopmentMode.Development
                sb.AppendLine(HTMLComment("HTMLCboTheme"))
        End Select
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString() & "<asp:DropDownList ID=""cboTheme"" runat=""server"" AutoPostBack=""True"">")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString() & "<asp:DropDownList ID=""cboTheme"" runat=""server"" AutoPostBack=""True"" OnSelectedIndexChanged = ""cboTheme_SelectedIndexChanged"">")

        End Select

        spaces.Inc()
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""base"" Value=""base""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""black-tie"" Value=""black-tie""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""blitzer"" Value=""blitzer""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""cupertino"" Value=""cupertino""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""dark-hive"" Value=""dark-hive""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""dot-luv"" Value=""dot-luv""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""eggplant"" Value=""eggplant""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""excite-bike"" Value=""excite-bike""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""flick"" Value=""flick""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""hot-sneaks"" Value=""hot-sneaks""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""humanity"" Value=""humanity""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""le-frog"" Value=""le-frog""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""mint-choc"" Value=""mint-choc""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""overcast"" Value=""overcast""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""pepper-grinder"" Value=""pepper-grinder""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""redmond"" Value=""redmond""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""smoothness"" Value=""smoothness""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""south-street"" Value=""south-street""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""start"" Value=""start""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""sunny"" Value=""sunny""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""swanky-purse"" Value=""swanky-purse""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""trontastic"" Value=""trontastic""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""ui-darkness"" Value=""ui-darkness""></asp:ListItem>")
        sb.AppendLine(spaces.ToString() & "<asp:ListItem Text=""ui-lightness"" Value=""ui-lightness""></asp:ListItem>")
        spaces.Dec()
        sb.AppendLine(spaces.ToString() & "</asp:DropDownList>")

    End Sub

    Public Shared Sub grdRowCreatedFunction(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.Sorting = False Then
            Exit Sub
        End If
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "grdRowCreatedFunction")
        End If

        Dim CanOnRowDataBound As Boolean = False
        Select Case TableGen.CodeType
            Case CodeTypeEnum.CS2005
                Select Case TableGen.Paging
                    Case PagingEnum.HighSpeed
                        Select Case TableGen.ViewType
                            Case ViewTypeEnum.GridView
                                CanOnRowDataBound = True
                        End Select
                End Select
                Select Case TableGen.EditKeyPassing
                    Case EditKeyPassingEnum.Inline
                        CanOnRowDataBound = True
                End Select
        End Select


        If CanOnRowDataBound Then
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "Protected Sub grd_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grd.RowCreated")

                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "protected void grd_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)")
                    sb.AppendLine(spaces.ToString & "{")
            End Select
            spaces.Inc()

            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "If e.Row.RowType = DataControlRowType.Header Then")
                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "if ( e.Row.RowType == DataControlRowType.Header )")
                    sb.AppendLine(spaces.ToString & "{")
            End Select
            spaces.Inc()
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "For Each Cell As TableCell In e.Row.Cells")
                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "foreach (TableCell Cell in e.Row.Cells)")
                    sb.AppendLine(spaces.ToString & "{")
            End Select
            spaces.Inc()
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "If Cell.HasControls Then")
                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "if ( Cell.HasControls() )")
                    sb.AppendLine(spaces.ToString & "{")
            End Select
            spaces.Inc()

            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "Dim Button As LinkButton = DirectCast(Cell.Controls(0), LinkButton)")
                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "LinkButton Button = (LinkButton)Cell.Controls[0];")
            End Select

            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "If IsNothing(Button) = False Then")

                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "if ( Button != null )")
                    sb.AppendLine(spaces.ToString & "{")
            End Select
            spaces.Inc()
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "Dim DivTextAndImage As New HtmlGenericControl(""div"")")

                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "HtmlGenericControl DivTextAndImage = new HtmlGenericControl(""div"");")

            End Select
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "Dim DivText As New HtmlGenericControl(""div"")")

                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "HtmlGenericControl DivText = new HtmlGenericControl(""div"");")

            End Select
            sb.AppendLine(spaces.ToString & "DivText.InnerText = Button.Text" & EndStatement(TableGen))
            sb.AppendLine(spaces.ToString & "DivText.Style.Add(""float"", ""left"")" & EndStatement(TableGen))
            sb.AppendLine(spaces.ToString & "DivTextAndImage.Controls.Add(DivText)" & EndStatement(TableGen))
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "Dim DivImage As New HtmlGenericControl(""div"")")

                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "HtmlGenericControl DivImage = new HtmlGenericControl(""div"")" & EndStatement(TableGen))

            End Select
            sb.AppendLine("")
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "If Session(""" & TableGen.SafeTableName & ".SortExpression"") = Button.CommandArgument Then")

                Case CodeTypeEnum.CS2005

                    sb.AppendLine(spaces.ToString & "if ( Convert.ToString(Session[""" & TableGen.SafeTableName & ".SortExpression""]) == Button.CommandArgument ) ")
                    sb.AppendLine(spaces.ToString & "{")

            End Select
            spaces.Inc()
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "If Session(""" & TableGen.SafeTableName & ".SortDirection"") = ""ASC"" Then")

                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "if ( Convert.ToString(Session[""" & TableGen.SafeTableName & ".SortDirection""]) == ""ASC"" )")
                    sb.AppendLine(spaces.ToString & "{")

            End Select
            spaces.Inc()
            sb.AppendLine(spaces.ToString & "DivImage.Attributes.Add(""class"", ""ui-icon ui-icon-triangle-1-n"")" & EndStatement(TableGen))
            spaces.Dec()
            GetElse(sb, spaces, TableGen)
            spaces.Inc()
            sb.AppendLine(spaces.ToString & "DivImage.Attributes.Add(""class"", ""ui-icon ui-icon-triangle-1-s"")" & EndStatement(TableGen))
            spaces.Dec()
            GetEndIf(sb, spaces, TableGen)
            spaces.Dec()
            GetElse(sb, spaces, TableGen)
            spaces.Inc()
            sb.AppendLine(spaces.ToString & "DivImage.Attributes.Add(""class"", ""ui-icon ui-icon-carat-2-n-s"")" & EndStatement(TableGen))
            spaces.Dec()
            GetEndIf(sb, spaces, TableGen)
            sb.AppendLine(spaces.ToString & "DivImage.Style.Add(""float"", ""right"")" & EndStatement(TableGen))
            sb.AppendLine(spaces.ToString & "DivTextAndImage.Controls.Add(DivImage)" & EndStatement(TableGen))
            sb.AppendLine(spaces.ToString & "Button.Controls.Add(DivTextAndImage)" & EndStatement(TableGen))
            spaces.Dec()
            GetEndIf(sb, spaces, TableGen)
            spaces.Dec()
            GetEndIf(sb, spaces, TableGen)
            spaces.Dec()
            Select Case TableGen.CodeType
                Case CodeTypeEnum.VB2005
                    sb.AppendLine(spaces.ToString & "Next")
                Case CodeTypeEnum.CS2005
                    sb.AppendLine(spaces.ToString & "}")
            End Select

            spaces.Dec()
            GetEndIf(sb, spaces, TableGen)
            spaces.Dec()
            GetEndSub(sb, spaces, TableGen)
        End If

    End Sub

    Public Shared Sub ASPXScriptSection(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        Select Case TableGen.DevelopmentMode
            Case DevelopmentMode.Development
                sb.AppendLine(HTMLComment("ASPXScriptSection"))
        End Select
        sb.AppendLine(spaces.ToString() & "<script src=""http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"" type=""text/javascript""></script>")
        sb.AppendLine()
        'sb.AppendLine(spaces.ToString() & "<%-- v1.8rc1 --%>")
        'sb.AppendLine(spaces.ToString() & "<script src=""jquery-ui-1.8rc1.min.js"" type=""text/javascript""></script>")
        sb.AppendLine(spaces.ToString() & "<script src=""http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.js"" type=""text/javascript""></script>")

        'sb.AppendLine(Spaces.ToString() & "<script src=""jquery.ui.core.js"" type=""text/javascript""></script>")
        'sb.AppendLine(Spaces.ToString() & "<script src=""jquery.ui.widget.js"" type=""text/javascript""></script>")
        sb.AppendLine(spaces.ToString() & "<script src=""jquery.ui.button.js"" type=""text/javascript""></script>")


        If TableGen.IsAnyColumnDateUsingDateTimePicker() Then
            sb.AppendLine(spaces.ToString() & "<script src=""jquery.ui.datetimepicker.js"" type=""text/javascript""></script>")
        End If

        sb.AppendLine()

        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                'sb.AppendLine()
                'sb.AppendLine(spaces.ToString() & "<script type=""text/javascript"" src=""jquery.fancybox-1.3.0.pack.js""></script>")
                'sb.AppendLine(spaces.ToString() & "<script src=""ui.draggable.min.js"" type=""text/javascript""></script>")
                'sb.AppendLine(spaces.ToString() & "<script src=""ui.resizable.min.js"" type=""text/javascript""></script>")
                'sb.AppendLine(spaces.ToString() & "<script src=""ui.dialog.min.js"" type=""text/javascript""></script>")
                'sb.AppendLine(spaces.ToString() & "<script src=""jquery.bgiframe.min.js"" type=""text/javascript""></script>")
        End Select

        sb.AppendLine(spaces.ToString() & "<script type=""text/javascript"">")
        spaces.Inc()
        sb.AppendLine(spaces.ToString() & "$(function() {")
        spaces.Inc()

        sb.AppendLine(spaces.ToString() & "EndRequestHandler();")
        spaces.Dec()
        sb.AppendLine(spaces.ToString() & "});")

        sb.AppendLine(spaces.ToString() & "function EndRequestHandler() {")
        spaces.Inc()
        JQueryControlsDefinition(spaces, sb, TableGen)
        spaces.Dec()
        sb.AppendLine(spaces.ToString() & "}")

        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                sb.AppendLine(spaces.ToString() & "function body_onLoad() {")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "}")
        End Select


        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                sb.AppendLine(spaces.ToString() & "function GridClick( s )")
                sb.AppendLine(spaces.ToString() & "{")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "document.getElementById('ID').value = s;")
                sb.AppendLine(spaces.ToString() & "$('#cmdLoad').click();")
                sb.AppendLine(spaces.ToString() & "$('#dialog').dialog('open');")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "}")

            Case Else
                Select Case TableGen.ViewType
                    Case ViewTypeEnum.GridView
                    Case ViewTypeEnum.Repeater
                        sb.AppendLine(spaces.ToString() & "function GridClick( s )")
                        sb.AppendLine(spaces.ToString() & "{")
                        spaces.Inc()
                        sb.AppendLine(spaces.ToString() & "document.getElementById('RowClick').value = s;")
                        sb.AppendLine(spaces.ToString() & "document.getElementById('cmdLoad').click();")
                        spaces.Dec()
                        sb.AppendLine(spaces.ToString() & "}")
                    Case ViewTypeEnum.CodeBehind
                        sb.AppendLine(spaces.ToString() & "function GridClick( s )")
                        sb.AppendLine(spaces.ToString() & "{")
                        spaces.Inc()
                        sb.AppendLine(spaces.ToString() & "document.getElementById('RowClick').value = s;")
                        sb.AppendLine(spaces.ToString() & "document.getElementById('cmdLoad').click();")
                        spaces.Dec()
                        sb.AppendLine(spaces.ToString() & "}")
                End Select
        End Select
        spaces.Dec()
        sb.AppendLine(spaces.ToString() & "</script>")
    End Sub

    Public Shared Sub JQueryControlsDefinition(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)

        sb.AppendLine(spaces.ToString() & "$('#cmdAddNew').button();")

        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline

                sb.AppendLine(spaces.ToString() & "$('#cmdAddNew').click(function() {")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "document.getElementById('ID').value = '';")

                For Each Column As PCGColumn In TableGen.Columns
                    If Column.IsDisplayColumn = True Then
                        sb.AppendLine(spaces.ToString & "$(""#" & Column.ControlName("Dialog") & """).val('');")
                    End If
                Next
                sb.AppendLine(spaces.ToString() & "$('#dialog').dialog('open');")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "});")

                For Each Column As PCGColumn In TableGen.Columns
                    If Column.IsDisplayColumn = True Then
                        If Column.IsDate Then
                            If Column.DataFormat.ToUpper = "DATETIME" Then
                                JQueryDateTimeSection(sb, Column.ControlName("Dialog"), spaces)
                            Else
                                JQueryDateSection(sb, Column.ControlName("Dialog"), spaces)
                            End If
                            'sb.AppendLine(spaces.ToString & "$(""#" & Column.ControlName("Dialog") & """).val('');")
                        End If
                    End If
                Next

        End Select

        If TableGen.IsAnyColumnSearchable Then
            sb.AppendLine(spaces.ToString() & "$('#cmdSearch').button();")
        End If
    

        If TableGen.Paging = PagingEnum.HighSpeed Then
            sb.AppendLine(spaces.ToString() & "$('#cmdFirst').button();")
            sb.AppendLine(spaces.ToString() & "$('#cmdNext').button();")
            sb.AppendLine(spaces.ToString() & "$('#cmdLast').button();")
            sb.AppendLine(spaces.ToString() & "$('#cmdPrevious').button();")
        End If

        For Each Column As PCGColumn In TableGen.Columns
            If Column.Search <> "None" Then
                Select Case Column.DataType.ToUpper
                    Case "DATETIME"
                        If Column.DataFormat.ToUpper = "DATETIME" Then
                            JQueryDateTimeSection(sb, Column.ControlNameSearch("From"), spaces)
                            JQueryDateTimeSection(sb, Column.ControlNameSearch("To"), spaces)
                        Else
                            JQueryDateSection(sb, Column.ControlNameSearch("From"), spaces)
                            JQueryDateSection(sb, Column.ControlNameSearch("To"), spaces)
                        End If
                End Select
            End If
        Next

        sb.AppendLine(spaces.ToString() & "$('.GridEditButton').button();")
        sb.AppendLine("")
        sb.AppendLine(spaces.ToString() & "$("".PCG-Content tr:gt(0)"").mouseover(function() {")
        spaces.Inc()
        sb.AppendLine(spaces.ToString() & "$(this).addClass(""ui-state-highlight"");")
        spaces.Dec()
        sb.AppendLine(spaces.ToString() & "});")
        sb.AppendLine("")
        sb.AppendLine(spaces.ToString() & "$("".PCG-Content tr:gt(0)"").mouseout(function() {")
        spaces.Inc()
        sb.AppendLine(spaces.ToString() & "$(this).removeClass(""ui-state-highlight"");")
        spaces.Dec()
        sb.AppendLine(spaces.ToString() & "});")


        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline

                sb.AppendLine(spaces.ToString() & "$(""#dialog"").dialog({")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "bgiframe: true,")
                sb.AppendLine(spaces.ToString() & "resizable: false, // true is currently buggy across browsers(but toleratable)")
                sb.AppendLine(spaces.ToString() & "width: screen.width * 0.4,")
                sb.AppendLine(spaces.ToString() & "//height: 100,")
                sb.AppendLine(spaces.ToString() & "modal: true,")
                sb.AppendLine(spaces.ToString() & "autoOpen: false,")

                sb.AppendLine(spaces.ToString() & "buttons: {")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "'Save': function() {")
                For Each Column As PCGColumn In TableGen.Columns
                    If Column.IsDisplayColumn = True Then
                        If Column.LinkTableName.Length > 0 Then
                            sb.AppendLine(spaces.ToString & "var cbo" & Column.SafeParameterName("Dialog") & " = $(""#cbo" & Column.SafeParameterName("Dialog") & """).val();")
                            sb.AppendLine(spaces.ToString & "if ( cbo" & Column.SafeParameterName("Dialog") & " == null ) {")
                            sb.AppendLine(spaces.ToString & "$(""#" & Column.ControlName() & """).val('');")
                            sb.AppendLine(spaces.ToString & "} else {")
                            sb.AppendLine(spaces.ToString & "$(""#" & Column.ControlName() & """).val($(""#cbo" & Column.SafeParameterName("Dialog") & """).val());")
                            sb.AppendLine(spaces.ToString & "}")
                        Else
                            If Column.IsCheckBoxColumn Then
                                sb.AppendLine(spaces.ToString & "$(""#" & Column.ControlName() & """).attr('checked',$(""#" & Column.ControlName("Dialog") & """).is(':checked'));")

                            Else
                                sb.AppendLine(spaces.ToString & "$(""#" & Column.ControlName() & """).val($(""#" & Column.ControlName("Dialog") & """).val());")
                            End If
                        End If

                    End If
                Next

                sb.AppendLine(spaces.ToString() & "$(this).dialog('close');")
                sb.AppendLine(spaces.ToString() & "$(""#cmdSave"").click();")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "},")
                sb.AppendLine(spaces.ToString() & "Cancel: function() {")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "$(this).dialog('close');")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "}, ")
                sb.AppendLine(spaces.ToString() & "'Delete': function() {")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "$(this).dialog('close');")
                sb.AppendLine(spaces.ToString() & "$('#cmdDelete').click();")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "}")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "}")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "});")

                ' sb.AppendLine(spaces.ToString() & "$("":button"").button();")
        End Select
    End Sub

    Public Shared Sub ASPXUpdateDialog(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        Select Case TableGen.DevelopmentMode
            Case DevelopmentMode.Development
                sb.AppendLine(HTMLComment("ASPXUpdateDialog"))
        End Select
        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                sb.AppendLine(spaces.ToString() & "<div class=""hidden"">")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "<div id=""dialog"" title=""Update"">")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "<asp:UpdatePanel ID=""UpdatePanel1"" runat=""server"" >")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "<ContentTemplate>")
                spaces.Inc()

                ASPXTableEdit(spaces, sb, TableGen, "Dialog")



                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "</ContentTemplate>")
                sb.AppendLine(spaces.ToString() & "<Triggers>")
                spaces.Inc()
                sb.AppendLine(spaces.ToString() & "<asp:AsyncPostBackTrigger ControlID=""cmdLoad"" EventName=""Click"" />")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "</Triggers>")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "</asp:UpdatePanel>")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "</div>")
                Dim cmdLoad As String = "<asp:Button ID=""cmdLoad"" runat=""server"""
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.CS2005
                        cmdLoad = cmdLoad & " OnClick=""cmdLoad_Click"""
                End Select
                cmdLoad = cmdLoad & " />"
                sb.AppendLine(spaces.ToString() & cmdLoad)

                Dim cmdSave As String = "<asp:Button ID=""cmdSave"" runat=""server"""
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.CS2005
                        cmdSave = cmdSave & " OnClick=""cmdSave_Click"""
                End Select
                cmdSave = cmdSave & " />"
                sb.AppendLine(spaces.ToString() & cmdSave)

                Dim cmdDelete As String = "<asp:Button ID=""cmdDelete"" runat=""server"""
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.CS2005
                        cmdDelete = cmdDelete & " OnClick=""cmdDelete_Click"""
                End Select
                cmdDelete = cmdDelete & " />"
                sb.AppendLine(spaces.ToString() & cmdDelete)
                sb.AppendLine(spaces.ToString() & "<asp:TextBox ID=""ID"" runat=""server"" CssClass=""hidden""></asp:TextBox>")
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "</div>")
        End Select
    End Sub


    Public Shared Sub ASPXTableEdit(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, Optional ByVal Prefix As String = "")
        'If TableGen.DevelopmentMode = DevelopmentMode.Development Then
        '    AddComment(sb, TableGen, spaces, "[ASPXTableEdit]")
        'End If
        Select Case TableGen.DevelopmentMode
            Case DevelopmentMode.Development
                sb.AppendLine(HTMLComment("ASPXTableEdit"))
        End Select


        sb.AppendLine(spaces.ToString & "<table id=""tblEdit" & Prefix & TableGen.TableName & """ class=""ui-widget-content"">")
        spaces.Inc()
        For Each Column As PCGColumn In TableGen.Columns
            If Column.IsDisplayColumn = True Then

                sb.AppendLine(spaces.ToString & "<tr>")
                spaces.Inc()
                sb.AppendLine(spaces.ToString & "<td>")
                spaces.Inc()
                sb.AppendLine(spaces.ToString & "&nbsp;")
                spaces.Dec()
                sb.AppendLine(spaces.ToString & "</td>")
                sb.AppendLine(spaces.ToString & "<td class=""ui-widget-header"">")
                spaces.Inc()
                sb.AppendLine(spaces.ToString & Column.ColumnNameDescriptive)
                spaces.Dec()
                sb.AppendLine(spaces.ToString & "</td>")
                sb.AppendLine(spaces.ToString & "<td>")

                If Column.DisplayReadOnly = False And Column.LinkTableName.Length > 0 And Column.LinkTableKey.Length > 0 And Column.LinkTableValue.Length > 0 Then
                    spaces.Inc()
                    sb.Append(spaces.ToString & "<asp:DropDownList CssClass=""ui-widget"" id=""cbo" & Column.SafeParameterName(Prefix) & """ runat=""server""></asp:DropDownList>")
                    spaces.Dec()
                Else
                    spaces.Inc()
                    sb.Append(spaces.ToString & "<" & Column.ControlTypeName & " id=""" & Column.ControlName(Prefix) & """ runat=""server""")
                    If Column.DataType.ToUpper = "VARCHAR" Then
                        Try

                            If Column.Length() > 0 Then
                                sb.Append(" MaxLength=""" & Column.Length & """")
                            End If
                        Catch ex As Exception

                        End Try

                    End If

                    sb.AppendLine(" CssClass=""ui-widget""></" & Column.ControlTypeName & ">")

                    spaces.Dec()
                End If

                sb.AppendLine(spaces.ToString & "</td>")
                spaces.Dec()
                sb.AppendLine(spaces.ToString & "</tr>")
            End If
        Next


        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                'sb.AppendLine(spaces.ToString & "<tr>")
                'spaces.Inc()
                'sb.AppendLine(spaces.ToString & "<td>")
                'spaces.Inc()
                'sb.AppendLine(spaces.ToString & "&nbsp;")

                'spaces.Dec()
                'sb.AppendLine(spaces.ToString & "</td>")
                'sb.AppendLine(spaces.ToString & "<td>")
                'spaces.Inc()

                'sb.AppendLine(spaces.ToString & "<asp:Button ID=""cmdDialogDelete"" runat=""server"" Text=""Delete"" />")

                'spaces.Dec()
                'sb.AppendLine(spaces.ToString & "</td>")
                'sb.AppendLine(spaces.ToString & "<td>")
                'sb.AppendLine(spaces.ToString & "</td>")
                'spaces.Dec()
                'sb.AppendLine(spaces.ToString & "</tr>")


            Case Else
                sb.AppendLine(spaces.ToString & "<tr>")
                spaces.Inc()
                sb.AppendLine(spaces.ToString & "<td>")
                spaces.Inc()
                sb.AppendLine(spaces.ToString & "&nbsp;")
                spaces.Dec()
                sb.AppendLine(spaces.ToString & "</td>")
                sb.AppendLine(spaces.ToString & "<td>")
                spaces.Inc()
                Dim cmdDelete As New ASPXButton(TableGen.CodeType, "Delete")
                sb.AppendLine(spaces.ToString & cmdDelete.ToString)
                spaces.Dec()
                sb.AppendLine(spaces.ToString & "</td>")
                sb.AppendLine(spaces.ToString & "<td>")
                spaces.Inc()
                Dim cmdCancel As New ASPXButton(TableGen.CodeType, "Cancel")
                sb.AppendLine(spaces.ToString & cmdCancel.ToString & "&nbsp;&nbsp;&nbsp;")

                Dim cmdSave As New ASPXButton(TableGen.CodeType, "Save")
                sb.AppendLine(spaces.ToString & cmdSave.ToString)
                spaces.Dec()
                sb.AppendLine(spaces.ToString & "</td>")
                spaces.Dec()
                sb.AppendLine(spaces.ToString & "</tr>")
        End Select

        spaces.Dec()
        sb.AppendLine(spaces.ToString & "</table>")
    End Sub


    Public Shared Sub GetDetailASPXSaveClick(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetDetailASPXSaveClick]")
        End If

        Dim sql As String = ""

        sb.AppendLine("")
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Private Overloads Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "protected void cmdSave_Click(object sender, EventArgs e)")
                sb.AppendLine(spaces.ToString & "{")
        End Select

        sb.AppendLine("")

        spaces.Inc()

        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, "Declare String ID as set it to Request(""ID"") ")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005


                Select Case TableGen.EditKeyPassing
                    Case EditKeyPassingEnum.Inline
                        sb.AppendLine(spaces.ToString & "Dim ID As String = Me.ID.Text")
                    Case Else
                        sb.AppendLine(spaces.ToString & "Dim ID As String = " & GetAutonumberPassingField(TableGen) & "")
                End Select

            Case CodeTypeEnum.CS2005
                Select Case TableGen.EditKeyPassing
                    Case EditKeyPassingEnum.Inline
                        sb.AppendLine(spaces.ToString & "String ID = this.ID.Text;")
                    Case Else
                        sb.AppendLine(spaces.ToString & "String ID = " & GetAutonumberPassingField(TableGen) & ".ToString();")
                End Select

        End Select

        sb.AppendLine("")
        sb.Append(DeclareAndOpenConnection(spaces, TableGen))
        sb.AppendLine()

        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare " & GetDatabaseCommandClassName(TableGen) & " Object named Command ")
                AddComment(sb, TableGen, spaces, "To be used to invoke the Update or Insert statements ")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare " & GetDatabaseCommandClassName(TableGen) & " Object named Command ")
                AddComment(sb, TableGen, spaces, "To be used to invoke the Update or Insert statements ")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Dim Command As " & GetDatabaseCommandClassName(TableGen) & "")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & GetDatabaseCommandClassName(TableGen) & " Command;")
        End Select

        sb.AppendLine("")


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare string InsertSQL ")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare string InsertSQL ")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.Append(spaces.ToString & "Dim InsertSQL As String = """)
            Case CodeTypeEnum.CS2005
                sb.Append(spaces.ToString & "String InsertSQL = """)
        End Select

        sb.Append("Insert into [" & TableGen.SchemaName & "].[" & TableGen.TableName & "] (")
        sql = ""

        For Each AColumn As PCGColumn In TableGen.Columns

            If AColumn.IsDisplayColumn = True Then
                If AColumn.DisplayReadOnly = False Then
                    If Len(sql) > 0 Then
                        sql = sql & ", "
                    End If
                    sql = sql & "["
                    sql = sql & AColumn.ColumnName & "]"
                End If
            End If

        Next
        sb.Append(sql)

        sb.Append(" ) VALUES ( ")
        sql = ""
        For Each AColumn As PCGColumn In TableGen.Columns

            If AColumn.IsDisplayColumn = True Then
                If AColumn.DisplayReadOnly = False Then

                    If Len(sql) > 0 Then
                        sql = sql & ", "
                    End If
                    sql = sql & "@"
                    sql = sql & AColumn.SafeParameterName
                End If
            End If
        Next
        sb.Append(sql)

        sb.Append(" ) """)

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine("")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(";")
        End Select

        sb.AppendLine()


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare String UpdateSQL ")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare String UpdateSQL ")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.Append(spaces.ToString & "Dim UpdateSQL As String = """)
            Case CodeTypeEnum.CS2005
                sb.Append(spaces.ToString & "String UpdateSQL  = """)
        End Select

        sb.Append("Update [" & TableGen.SchemaName & "].[" & TableGen.TableName & "] set ")

        sql = ""
        For Each Column As PCGColumn In TableGen.Columns
            If Column.IsDisplayColumn = True Then
                If Column.DisplayReadOnly = False Then
                    If Len(sql) > 0 Then
                        sql = sql & ", ["
                    Else
                        sql = sql & "["
                    End If

                    sql = sql & Column.ColumnName & "] = @" & Column.SafeParameterName

                End If
            End If
        Next
        sb.Append(sql)


        sb.Append(" where [" & TableGen.AutoNumberColumn & "] = @" & TableGen.AutoNumberColumn & " """)

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine("")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(";")
        End Select

        sb.AppendLine("")

        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "if ID > 0 run the update ")
                AddComment(sb, TableGen, spaces, "if ID = 0 run the Insert")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "If the Length of ID > 0 then update the record in the database ")
                AddComment(sb, TableGen, spaces, "If the Length of ID = 0 then insert the record in the database. ")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "If String.IsNullOrEmpty(ID)  Then")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "if (String.IsNullOrEmpty(ID))")
                sb.AppendLine(spaces.ToString & "{")
        End Select

        spaces.Inc()


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Create a new Command object for inserting a new record. ")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Create a new Command object for inserting a new record. ")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Command = New " & GetDatabaseCommandClassName(TableGen) & "(InsertSQL, Connection)")

            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Command = new " & GetDatabaseCommandClassName(TableGen) & "(InsertSQL, Connection);")
        End Select


        ''''''''
        ' Patch 3/18/2010
        ' Capturing Primary Key Name
        For Each Column As PCGColumn In TableGen.Columns
            If Column.IsDisplayColumn = True Then
                If Column.DisplayReadOnly = False Then
                    If Column.ColumnName = TableGen.AutoNumberColumn Then
                        Select Case TableGen.CommentLevel
                            Case CommentLevelEnum.Basic
                                AddComment(sb, TableGen, spaces, " ")
                                AddComment(sb, TableGen, spaces, "Set the @" & TableGen.AutoNumberColumn & " field for updates. ")

                            Case CommentLevelEnum.Verbose
                                AddComment(sb, TableGen, spaces, " ")
                                AddComment(sb, TableGen, spaces, "Set the @" & TableGen.AutoNumberColumn & " field for updates. ")

                        End Select


                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & TableGen.AutoNumberColumn & """, ID)")
                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & TableGen.AutoNumberColumn & """, ID);")
                        End Select
                    End If
                End If
            End If
        Next

        ''''''''


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "We are doing an insert ")
            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "We are doing an insert ")
        End Select


        spaces.Dec()

        GetElse(sb, spaces, TableGen)

        spaces.Inc()


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Set the command object with the update sql and connection. ")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Set the command object with the update sql and connection. ")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Command = New " & GetDatabaseCommandClassName(TableGen) & "(UpdateSQL, Connection)")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Command = new " & GetDatabaseCommandClassName(TableGen) & "(UpdateSQL, Connection);")
        End Select


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Set the @" & TableGen.AutoNumberColumn & " field for updates. ")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Set the @" & TableGen.AutoNumberColumn & " field for updates. ")

        End Select


        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & TableGen.AutoNumberColumn & """, ID)")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & TableGen.AutoNumberColumn & """, ID);")
        End Select

        spaces.Dec()
        GetEndIf(sb, spaces, TableGen)

        For Each Column As PCGColumn In TableGen.Columns
            If Column.IsDisplayColumn = True And Column.DisplayReadOnly = False Then
                If Column.DisplayReadOnly = False And Column.LinkTableName.Length > 0 And Column.LinkTableKey.Length > 0 And Column.LinkTableValue.Length > 0 Then
                    SaveClickComboBoxAddParameterLine(spaces, sb, TableGen, Column)
                Else
                    If Column.IsIdentity = False Then
                        Select Case Column.DataType.ToUpper
                            Case "DATETIME", "TIMESTAMP", "SMALLDATETIME"
                                Select Case TableGen.CodeType
                                    Case CodeTypeEnum.VB2005
                                        sb.AppendLine(spaces.ToString & "If IsDate(" & Column.ControlName & "." & Column.ControlAccessor & ") Then")
                                        spaces.Inc()

                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, " & Column.ControlName & "." & Column.ControlAccessor & ")")
                                        spaces.Dec()

                                        GetElse(sb, spaces, TableGen)
                                        spaces.Inc()

                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, DBNull.Value)")
                                        spaces.Dec()

                                        GetEndIf(sb, spaces, TableGen)
                                    Case CodeTypeEnum.CS2005
                                        sb.AppendLine(spaces.ToString & "if ( IsDate(" & Column.ControlName & "." & Column.ControlAccessor & ") ) {")
                                        spaces.Inc()

                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, " & Column.ControlName & "." & Column.ControlAccessor & ");")
                                        spaces.Dec()
                                        sb.AppendLine(spaces.ToString & "} else {")
                                        spaces.Inc()
                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, DBNull.Value);")
                                        spaces.Dec()

                                        sb.AppendLine(spaces.ToString & "}")
                                End Select
                            Case "INT", "AUTONUMBER", "DECIMAL", "FLOAT", "INT", "REAL", "SMALLINT", "TINYINT", "MONEY", "SMALLMONEY", "NUMERIC", "BIGINT"
                                Select Case TableGen.CodeType
                                    Case CodeTypeEnum.VB2005
                                        sb.AppendLine(spaces.ToString & "If IsNumeric(" & Column.ControlName & "." & Column.ControlAccessor & ") Then")
                                        spaces.Inc()
                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, " & Column.ControlName & "." & Column.ControlAccessor & ")")
                                        spaces.Dec()
                                        GetElse(sb, spaces, TableGen)
                                        spaces.Inc()
                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, DBNull.Value)")
                                        spaces.Dec()
                                        GetEndIf(sb, spaces, TableGen)
                                    Case CodeTypeEnum.CS2005
                                        sb.AppendLine(spaces.ToString & "if ( IsNumeric(" & Column.ControlName & "." & Column.ControlAccessor & ") ) {")
                                        spaces.Inc()
                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, " & Column.ControlName & "." & Column.ControlAccessor & ");")
                                        spaces.Dec()
                                        sb.AppendLine(spaces.ToString & "} else {")
                                        spaces.Inc()
                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, DBNull.Value);")
                                        spaces.Dec()
                                        sb.AppendLine(spaces.ToString & "}")
                                End Select

                            Case "VARCHAR", "NCHAR", "NVARCHAR", "NTEXT", "TEXT", "CHAR"
                                Select Case TableGen.CodeType
                                    Case CodeTypeEnum.VB2005
                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, " & Column.ControlName & "." & Column.ControlAccessor & ")")
                                    Case CodeTypeEnum.CS2005
                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, " & Column.ControlName & "." & Column.ControlAccessor & ");")
                                End Select
                            Case "BIT"
                                Select Case TableGen.CodeType
                                    Case CodeTypeEnum.VB2005
                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, " & Column.ControlName & "." & Column.ControlAccessor & ")")
                                    Case CodeTypeEnum.CS2005
                                        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, " & Column.ControlName & "." & Column.ControlAccessor & ");")
                                End Select
                            Case Else
                                Debug.WriteLine(Column.DataType.ToUpper & "needs mapping")
                        End Select
                    End If
                End If
                sb.AppendLine("")
            End If
        Next


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Run the sql command against the database with no return values ")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Run the sql command against the database with no return values ")

        End Select

        CommandDotExecuteNonQuery(sb, TableGen, spaces)


        ConnectionDotClose(sb, TableGen, spaces)


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Go to the Summary page ")
            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Go to the Summary page ")
        End Select


        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                sb.AppendLine(spaces.ToString & "BindGrid()" & EndStatement(TableGen))
            Case Else
                sb.AppendLine(EditVBReturnToMaster(TableGen))
        End Select


        spaces.Dec()


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "End event Save click ")
            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "End event Save click ")
        End Select


        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "End Sub")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "}")
        End Select

    End Sub

    Public Shared Sub LoadSingleRecordControls(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, Optional ByVal Prefix As String = "")
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[LoadSingleRecordControls]")
        End If

        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                'do nothing
            Case Else
                LoadClickCallLoadComboBoxes(spaces, sb, TableGen, Prefix)
        End Select

        sb.Append(DeclareAndOpenConnection(spaces, TableGen))


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "if " & GetAutonumberPassingField(TableGen) & " > 0 then this is an edit")
                AddComment(sb, TableGen, spaces, "if " & GetAutonumberPassingField(TableGen) & " = 0 then this is an insert")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "if " & GetAutonumberPassingField(TableGen) & " > 0 then this is an edit")
                AddComment(sb, TableGen, spaces, "if " & GetAutonumberPassingField(TableGen) & " = 0 then this is an insert")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "If Len(" & GetAutonumberPassingField(TableGen) & ") > 0 Then")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "if (" & GetAutonumberPassingField(TableGen) & ".ToString().Length > 0 )")
                sb.AppendLine(spaces.ToString & "{")
        End Select

        spaces.Inc()

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Dim sql as string =""select * from [" & TableGen.SchemaName & "].[" & TableGen.TableName & "] where [" & TableGen.AutoNumberColumn & "] = @" & TableGen.AutoNumberColumn & """")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "String sql =""select * from [" & TableGen.SchemaName & "].[" & TableGen.TableName & "] where [" & TableGen.AutoNumberColumn & "] = @" & TableGen.AutoNumberColumn & """;")
        End Select


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare SQLCommand Object named Command")
                AddComment(sb, TableGen, spaces, "Create a new Command object with a select statement that will open the row referenced by Request(""ID"")")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare SQLCommand Object named Command")
                AddComment(sb, TableGen, spaces, "Create a new Command object with a select statement that will open the row referenced by Request(""ID"")")

        End Select

        sb.AppendLine(GetCommandObjectWithConstructor(TableGen, New Space(4)))


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, " 'Set the @" & TableGen.AutoNumberColumn & " parameter in the Command select query")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, " 'Set the @" & TableGen.AutoNumberColumn & " parameter in the Command select query")

        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & TableGen.AutoNumberColumn & """, " & GetAutonumberPassingField(TableGen) & ")")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & TableGen.AutoNumberColumn & """, " & GetAutonumberPassingField(TableGen) & ");")
        End Select


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare a " & GetDatabaseReaderClassName(TableGen) & " Ojbect")
                AddComment(sb, TableGen, spaces, "Load it with the Command's select statement")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare a " & GetDatabaseReaderClassName(TableGen) & " Ojbect")
                AddComment(sb, TableGen, spaces, "Load it with the Command's select statement")

        End Select

        DimReaderAsSQLDataReaderEqualsCommandDotExecuteReader(sb, TableGen, spaces)

        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "If at least one record was found")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "If at least one record was found")

        End Select

        GetIfReaderDotRead(sb, spaces, TableGen)

        For Each Column As PCGColumn In TableGen.Columns
            If Column.IsDisplayColumn = True Then
                If Column.DisplayReadOnly = False And Column.LinkTableName.Length > 0 And Column.LinkTableKey.Length > 0 And Column.LinkTableValue.Length > 0 Then
                    sb.AppendLine(spaces.ToString & "cbo" & Column.SafeParameterName(Prefix) & ".SelectedValue = Reader" & GetStringIndex(TableGen, Column.ColumnName) & ".ToString()" & EndStatement(TableGen))
                Else
                    Select Case TableGen.CodeType
                        Case CodeTypeEnum.VB2005
                            Select Case Column.DataType.ToUpper
                                Case "BIT"
                                    If TableGen.DevelopmentMode = DevelopmentMode.Development Then
                                        AddComment(sb, TableGen, spaces, "[LoadSingleRecordControls].columnLoop.vb.bit")
                                    End If
                                    If Column.AllowNulls = True Then
                                        sb.AppendLine(spaces.ToString & "If IsDBNull(Reader(""" & Column.ColumnName & """)) = False Then ")
                                        spaces.Inc()
                                    End If
                                    sb.AppendLine(spaces.ToString & Column.ControlName(Prefix) & "." & Column.ControlAccessor & " = Reader(""" & Column.ColumnName & """).ToString()")
                                    If Column.AllowNulls = True Then
                                        spaces.Dec()
                                        GetEndIf(sb, spaces, TableGen)
                                    End If

                                Case Else
                                    sb.AppendLine(spaces.ToString & Column.ControlName(Prefix) & "." & Column.ControlAccessor & " = Reader(""" & Column.ColumnName & """).ToString()")
                            End Select

                        Case CodeTypeEnum.CS2005
                            Select Case Column.DataType.ToUpper
                                Case "BIT"
                                    If Column.AllowNulls = True Then
                                        sb.AppendLine(spaces.ToString & "if (Reader[""" & Column.ColumnName & """] == DBNull.Value ) {")
                                        spaces.Inc()
                                        sb.AppendLine(spaces.ToString & Column.ControlName(Prefix) & "." & Column.ControlAccessor & " = false;")
                                        spaces.Dec()
                                        GetElse(sb, spaces, TableGen)
                                        spaces.Inc()

                                    End If
                                    sb.AppendLine(spaces.ToString & Column.ControlName(Prefix) & "." & Column.ControlAccessor & " = bool.Parse(Reader[""" & Column.ColumnName & """].ToString());")
                                    If Column.AllowNulls = True Then
                                        spaces.Dec()
                                        GetEndIf(sb, spaces, TableGen)

                                    End If
                                Case Else
                                    sb.AppendLine(spaces.ToString & Column.ControlName(Prefix) & "." & Column.ControlAccessor & " = Reader[""" & Column.ColumnName & """].ToString();")
                            End Select
                    End Select
                End If
            End If
        Next

        spaces.Dec()
        GetEndIf(sb, spaces, TableGen)

        ReaderDotClose(sb, TableGen, spaces)

        ConnectionDotClose(sb, TableGen, spaces)


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "The length of ID equals zero.")
                AddComment(sb, TableGen, spaces, "This is an insert so don't preload any data.")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "The length of ID equals zero.")
                AddComment(sb, TableGen, spaces, "This is an insert so don't preload any data.")
        End Select

        spaces.Dec()
        GetElse(sb, spaces, TableGen)


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Since this is an insert then you can't delete it yet because it's not in the database.")
            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Since this is an insert then you can't delete it yet because it's not in the database.")
        End Select

        spaces.Inc()

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "cmdDelete.Visible = False")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "cmdDelete.Visible = false;")
        End Select
        spaces.Dec()


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "end of if Reader.Read ")
            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "end of if Reader.Read ")
        End Select

        GetEndIf(sb, spaces, TableGen)

    End Sub


    Public Shared Sub GetDetailASPXDeleteClick(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetDetailASPXDeleteClick]")
        End If
        sb.AppendLine("")


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Event handler for Delete clicks ")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Event handler for Delete clicks ")
        End Select

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Protected Sub cmdDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdDelete.Click")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "protected void cmdDelete_Click(object sender, EventArgs e)")
                sb.AppendLine(spaces.ToString & "{")
        End Select
        spaces.Inc()

        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & "If Len(" & GetAutonumberPassingField(TableGen) & ") > 0 Then")
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & "if (" & GetAutonumberPassingField(TableGen) & ".ToString().Length > 0 )")
                        sb.AppendLine(spaces.ToString & "{")
                End Select
                spaces.Inc()
        End Select

        sb.Append(DeclareAndOpenConnection(spaces, TableGen))

        sb.AppendLine("")
        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Dim sql as string =""delete from [" & TableGen.SchemaName & "].[" & TableGen.TableName & "] where [" & TableGen.AutoNumberColumn & "] = @" & TableGen.AutoNumberColumn & """")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "String sql =""delete from [" & TableGen.SchemaName & "].[" & TableGen.TableName & "] where [" & TableGen.AutoNumberColumn & "] = @" & TableGen.AutoNumberColumn & """;")
        End Select


        Select Case TableGen.CommentLevel
            Case CommentLevelEnum.Basic
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare SQLCommand Object named Command")
                AddComment(sb, TableGen, spaces, "Create a new Command object with a delete statement that will removed the current item being edited")

            Case CommentLevelEnum.Verbose
                AddComment(sb, TableGen, spaces, " ")
                AddComment(sb, TableGen, spaces, "Declare SQLCommand Object named Command")
                AddComment(sb, TableGen, spaces, "Create a new Command object with a delete statement that will removed the current item being edited")

        End Select


        sb.AppendLine(GetCommandObjectWithConstructor(TableGen, spaces))

        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & TableGen.AutoNumberColumn & """, " & GetAutonumberPassingField(TableGen) & ")")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & TableGen.AutoNumberColumn & """, " & GetAutonumberPassingField(TableGen) & ");")
        End Select

        CommandDotExecuteNonQuery(sb, TableGen, spaces)


        sb.AppendLine("")

        ConnectionDotClose(sb, TableGen, spaces)

        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
        End Select

        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                spaces.Dec()
                GetEndIf(sb, spaces, TableGen)
                sb.AppendLine(spaces.ToString & "BindGrid()" & EndStatement(TableGen))

            Case Else
                sb.Append(EditVBReturnToMaster(TableGen))
        End Select

        spaces.Dec()
        GetEndSub(sb, spaces, TableGen)
    End Sub

    Public Shared Sub SaveClickComboBoxAddParameterLine(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, ByVal Column As PCGColumn)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[SaveClickComboBoxAddParameterLine]")
        End If

        Dim ControlName As String = ""
        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                ControlName = "txt" & Column.SafeParameterName & ".Text"
            Case Else
                ControlName = "cbo" & Column.SafeParameterName & ".SelectedValue"
        End Select


        Select Case TableGen.CodeType
            Case CodeTypeEnum.VB2005
                sb.AppendLine(spaces.ToString & "if " & ControlName & ".Length > 0 then ")
            Case CodeTypeEnum.CS2005
                sb.AppendLine(spaces.ToString & "if ( " & ControlName & ".Length > 0 ) ")
                sb.AppendLine(spaces.ToString & "{ ")
        End Select
        spaces.Inc()

        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, " & ControlName & ")" & EndStatement(TableGen))
        spaces.Dec()
        GetElse(sb, spaces, TableGen)

        spaces.Inc()

        sb.AppendLine(spaces.ToString & "Command.Parameters." & CommandParametersAddWithValue(TableGen) & "(""@" & Column.SafeParameterName & """, DBNull.Value )" & EndStatement(TableGen))

        spaces.Dec()
        GetEndIf(sb, spaces, TableGen)

    End Sub

    Public Shared Sub LoadClickCallLoadComboBoxes(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, Optional ByVal PreFix As String = "")
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[LoadClickCallLoadComboBoxes]")
        End If
        ' Load combo Box.
        sb.AppendLine()
        For Each Column As PCGColumn In TableGen.Columns
            If Column.IsDisplayColumn = True Then
                If Column.DisplayReadOnly = False Then
                    If Column.LinkTableName.Length > 0 And Column.LinkTableKey.Length > 0 And Column.LinkTableValue.Length > 0 Then
                        sb.AppendLine(spaces.ToString & "Loadcbo" & Column.SafeParameterName(PreFix) & "()" & EndStatement(TableGen))
                    End If
                End If
            End If
        Next
    End Sub

    Public Shared Sub LoadSubComboBoxSearchInitializeCodeVB(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, Optional ByVal PreFix As String = "")
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[LoadSubComboBoxSearchInitializeCodeVB]")
        End If
        For Each Column As PCGColumn In TableGen.Columns
            If Column.IsDisplayColumn = True Then
                If Column.Search <> "None" Then
                    If Column.LinkTableName.Length > 0 And Column.LinkTableKey.Length > 0 And Column.LinkTableValue.Length > 0 Then
                        sb.AppendLine()
                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & "Protected Sub Loadcbo" & Column.SafeParameterName(PreFix) & "() ")
                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & "protected void Loadcbo" & Column.SafeParameterName(PreFix) & "()")
                                sb.AppendLine(spaces.ToString & "{")
                        End Select
                        spaces.Inc()

                        sb.Append(DeclareAndOpenConnection(spaces, TableGen))

                        Dim SQL As String = "select " & Column.LinkTableKey
                        If Column.LinkTableKey <> Column.LinkTableValue Then
                            SQL = SQL & ", " & Column.LinkTableValue
                        End If
                        SQL = SQL & " from [" & Column.LinkTableName & "] order by " & Column.LinkTableValue

                        SQL = """" & SQL & """" & EndStatement(TableGen)
                        sb.AppendLine()

                        Select Case TableGen.CommentLevel
                            Case CommentLevelEnum.Basic
                                AddComment(sb, TableGen, spaces, "Select statement that loads the combo box for searching the " & Column.ColumnName & " column")

                            Case CommentLevelEnum.Verbose
                                AddComment(sb, TableGen, spaces, "The Key column is: " & Column.LinkTableKey)
                                AddComment(sb, TableGen, spaces, "The Display column is: " & Column.LinkTableValue)
                                AddComment(sb, TableGen, spaces, "The Table is: " & Column.LinkTableName)
                                AddComment(sb, TableGen, spaces, "Sorted by " & Column.LinkTableValue)

                        End Select

                        sb.AppendLine(DimVariableAsClassName(TableGen, spaces, "sql", "String", SQL))

                        sb.AppendLine()

                        Select Case TableGen.CommentLevel
                            Case CommentLevelEnum.Basic
                                AddComment(sb, TableGen, spaces, "Set the Command variable to a new instance of a " & GetDatabaseCommandClassName(TableGen) & " object")
                                AddComment(sb, TableGen, spaces, "Initialize it with the sql and Connection")

                            Case CommentLevelEnum.Verbose
                                AddComment(sb, TableGen, spaces, "Set the Command variable to a new instance of a " & GetDatabaseCommandClassName(TableGen) & " object")
                                AddComment(sb, TableGen, spaces, "Initialize it with the sql and Connection")

                        End Select



                        sb.Append(DimVariableAsNewClassName(TableGen, spaces, "Command", GetDatabaseCommandClassName(TableGen), "sql, Connection"))
                        sb.AppendLine()

                        Select Case TableGen.CommentLevel
                            Case CommentLevelEnum.Basic
                                AddComment(sb, TableGen, spaces, "Set the DataTextField to " & Column.LinkTableValue)
                                AddComment(sb, TableGen, spaces, "The DataTextField linked to the field that is to be displayed in the combo box.")

                            Case CommentLevelEnum.Verbose
                                AddComment(sb, TableGen, spaces, "Set the DataTextField to " & Column.LinkTableValue)
                                AddComment(sb, TableGen, spaces, "The DataTextField linked to the field that is to be displayed in the combo box.")

                        End Select

                        sb.AppendLine(spaces.ToString & "cbo" & Column.SafeParameterName(PreFix) & ".DataTextField = """ & Column.LinkTableValue & """" & EndStatement(TableGen))


                        Select Case TableGen.CommentLevel
                            Case CommentLevelEnum.Basic
                                sb.AppendLine()
                                AddComment(sb, TableGen, spaces, "Set the DataValueField to " & Column.LinkTableKey)
                                AddComment(sb, TableGen, spaces, "The DataTextField linked to the field that will be returned when an item is selected.")

                            Case CommentLevelEnum.Verbose
                                sb.AppendLine()
                                AddComment(sb, TableGen, spaces, "Set the DataValueField to " & Column.LinkTableKey)
                                AddComment(sb, TableGen, spaces, "The DataTextField linked to the field that will be returned when an item is selected.")

                        End Select

                        sb.AppendLine(spaces.ToString & "cbo" & Column.SafeParameterName(PreFix) & ".DataValueField = """ & Column.LinkTableKey() & """" & EndStatement(TableGen))


                        Select Case TableGen.CommentLevel
                            Case CommentLevelEnum.Basic

                            Case CommentLevelEnum.Verbose
                                sb.AppendLine()
                                AddComment(sb, TableGen, spaces, "When execute reader is called it returns a forward only result set.")
                                AddComment(sb, TableGen, spaces, "The result set is then assigned to the Datasource field.")

                        End Select

                        sb.AppendLine(spaces.ToString & "cbo" & Column.SafeParameterName(PreFix) & ".DataSource = Command.ExecuteReader()" & EndStatement(TableGen))


                        Select Case TableGen.CommentLevel
                            Case CommentLevelEnum.Basic

                            Case CommentLevelEnum.Verbose
                                sb.AppendLine()
                                AddComment(sb, TableGen, spaces, "Calling BindGrid loads binds the combobox and loads all the data up.")
                                AddComment(sb, TableGen, spaces, "based on the DataTextField and DataValueField fields set above.")

                        End Select

                        sb.AppendLine(spaces.ToString & "cbo" & Column.SafeParameterName(PreFix) & ".DataBind()" & EndStatement(TableGen))


                        Select Case TableGen.CommentLevel
                            Case CommentLevelEnum.Basic

                            Case CommentLevelEnum.Verbose
                                sb.AppendLine()
                                AddComment(sb, TableGen, spaces, "This does not really close the connection, but lets the connection pool know your not using the connection.")

                        End Select

                        ConnectionDotClose(sb, TableGen, spaces)

                        spaces.Dec()

                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005

                                Select Case TableGen.CommentLevel
                                    Case CommentLevelEnum.Basic

                                    Case CommentLevelEnum.Verbose
                                        sb.AppendLine()
                                        AddComment(sb, TableGen, spaces, "End Sub - Loadcbo" & Column.SafeParameterName)

                                End Select
                                sb.AppendLine(spaces.ToString & "End Sub")
                            Case CodeTypeEnum.CS2005

                                Select Case TableGen.CommentLevel
                                    Case CommentLevelEnum.Basic

                                    Case CommentLevelEnum.Verbose
                                        sb.AppendLine()
                                        AddComment(sb, TableGen, spaces, "End function - Loadcbo" & Column.SafeParameterName)

                                End Select
                                sb.AppendLine(spaces.ToString & "}")
                        End Select
                    End If
                End If
            End If
        Next



    End Sub

    Public Shared Sub LoadSubComboBoxInitializeCodeVB(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript, Optional ByVal PreFix As String = "")
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[LoadSubComboBoxInitializeCodeVB]")
        End If

        For Each Column As PCGColumn In TableGen.Columns
            If Column.IsDisplayColumn = True Then
                If Column.DisplayReadOnly = False Then
                    If Column.LinkTableName.Length > 0 And Column.LinkTableKey.Length > 0 And Column.LinkTableValue.Length > 0 Then
                        sb.AppendLine()
                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & "Protected Sub Loadcbo" & Column.SafeParameterName(PreFix) & "() ")
                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & "protected void Loadcbo" & Column.SafeParameterName(PreFix) & "()")
                                sb.AppendLine(spaces.ToString & "{")
                        End Select
                        spaces.Inc()

                        ' sb.AppendLine(Spaces.ToString & "Loadcbo" & Column.SafeParameterName & "()" & EndStatement(TableGen))

                        sb.Append(DeclareAndOpenConnection(spaces, TableGen))

                        Dim SQL As String = "select " & Column.LinkTableKey
                        If Column.LinkTableKey <> Column.LinkTableValue Then
                            SQL = SQL & ", " & Column.LinkTableValue
                        End If
                        SQL = SQL & " from [" & Column.LinkTableName & "] order by " & Column.LinkTableValue

                        SQL = """" & SQL & """" & EndStatement(TableGen)
                        sb.AppendLine(DimVariableAsClassName(TableGen, spaces, "sql", "String", SQL))

                        'Dim Command As New OleDbCommand("select SchoolID, SchoolName from [School] order by SchoolName", Connection)
                        sb.Append(DimVariableAsNewClassName(TableGen, spaces, "Command", GetDatabaseCommandClassName(TableGen), "sql, Connection"))

                        'cboSchoolID.DataTextField = "SchoolName"
                        sb.AppendLine(spaces.ToString & "cbo" & Column.SafeParameterName(PreFix) & ".DataTextField = """ & Column.LinkTableValue & """" & EndStatement(TableGen))

                        'cboSchoolID.DataValueField = "SchoolID"

                        sb.AppendLine(spaces.ToString & "cbo" & Column.SafeParameterName(PreFix) & ".DataValueField = """ & Column.LinkTableKey() & """" & EndStatement(TableGen))


                        'cboSchoolID.DataSource = Command.ExecuteReader

                        sb.AppendLine(spaces.ToString & "cbo" & Column.SafeParameterName(PreFix) & ".DataSource = Command.ExecuteReader()" & EndStatement(TableGen))


                        'cboSchoolID.DataBind()
                        sb.AppendLine(spaces.ToString & "cbo" & Column.SafeParameterName(PreFix) & ".DataBind()" & EndStatement(TableGen))
                        ConnectionDotClose(sb, TableGen, spaces)

                        spaces.Dec()
                        GetEndSub(sb, spaces, TableGen)
                    End If
                End If
            End If
        Next

    End Sub

    Public Shared Function HTMLComment(ByVal s As String) As String
        '<%--asdf--%>
        HTMLComment = "<%--" & s & "--%>"
    End Function

    Public Shared Sub GetProtectedSubcmdPreviousClick(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetProtectedSubcmdPreviousClick]")
        End If

        Select Case TableGen.Paging
            Case PagingEnum.HighSpeed
                sb.AppendLine("")
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & "Protected Sub cmdPrevious_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdPrevious.Click")
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & "protected void cmdPrevious_Click(object sender, EventArgs e)")
                        sb.AppendLine(spaces.ToString & "{")
                End Select
                spaces.Inc()
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & IfGreaterThan(ReadSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen), "1", TableGen))
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & IfGreaterThan("int.Parse(" & ReadSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & ")", "1", TableGen))
                End Select

                spaces.Inc()
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & " = " & ReadSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & " - 1" & EndStatement(TableGen))
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & " = int.Parse(" & ReadSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & ") - 1" & EndStatement(TableGen))
                End Select
                spaces.Dec()
                GetElse(sb, spaces, TableGen)

                spaces.Inc()
                sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & " = 1" & EndStatement(TableGen))
                spaces.Dec()
                GetEndIf(sb, spaces, TableGen)
                sb.AppendLine(spaces.ToString & "BindGrid()" & EndStatement(TableGen))
                spaces.Dec()
                GetEndSub(sb, spaces, TableGen)
        End Select
    End Sub

    Public Shared Sub GetProtectedSubcmdNextClick(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetProtectedSubcmdNextClick]")
        End If

        Select Case TableGen.Paging
            Case PagingEnum.HighSpeed
                sb.AppendLine("")

                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & "Protected Sub cmdNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdNext.Click")
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & "protected void cmdNext_Click(object sender, EventArgs e)")
                        sb.AppendLine(spaces.ToString & "{")
                End Select
                spaces.Inc()
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & " = " & ReadSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & " + 1" & EndStatement(TableGen))
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & " = int.Parse(" & ReadSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & ") + 1" & EndStatement(TableGen))
                End Select

                sb.AppendLine(spaces.ToString & "BindGrid()" & EndStatement(TableGen))
                spaces.Dec()
                GetEndSub(sb, spaces, TableGen)
        End Select
    End Sub


    Public Shared Sub GetProtectedSubcmdFirstClick(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetProtectedSubcmdFirstClick]")
        End If

        Select Case TableGen.Paging
            Case PagingEnum.HighSpeed

                sb.AppendLine("")
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & "Protected Sub cmdFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdFirst.Click")
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & "protected void cmdFirst_Click(object sender, EventArgs e)")
                        sb.AppendLine(spaces.ToString & "{")
                End Select
                spaces.Inc()
                sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".CurrentPage", TableGen) & " = " & "1" & EndStatement(TableGen))
                sb.AppendLine(spaces.ToString & "BindGrid()" & EndStatement(TableGen))
                spaces.Dec()
                GetEndSub(sb, spaces, TableGen)
        End Select
    End Sub

    Public Shared Sub GetProtectedSubgrdRowDataBound(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            AddComment(sb, TableGen, spaces, "[GetProtectedSubgrdRowDataBound]")
        End If

        Select Case TableGen.ViewType
            Case ViewTypeEnum.GridView
                sb.AppendLine()
                Select Case TableGen.CodeType
                    Case CodeTypeEnum.VB2005
                        sb.AppendLine(spaces.ToString & "Protected Sub grd_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grd.RowDataBound")
                    Case CodeTypeEnum.CS2005
                        sb.AppendLine(spaces.ToString & "protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)")
                        sb.AppendLine(spaces.ToString & "{")
                End Select
                spaces.Inc()
                Select Case TableGen.Paging
                    Case PagingEnum.HighSpeed
                        sb.AppendLine(spaces.ToString & IfEquals("e.Row.RowType", "DataControlRowType.Header", TableGen))
                        spaces.Inc()
                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".RecordsFound", TableGen) & " = grd.DataSource(""RecordSetCount"")" & EndStatement(TableGen))
                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & SetSessionField(TableGen.SafeTableName & ".RecordsFound", TableGen) & " = ((SqlDataReader)grd.DataSource)[""RecordSetCount""]" & EndStatement(TableGen))
                        End Select
                        sb.AppendLine(spaces.ToString & "UpdateLabels()" & EndStatement(TableGen))
                        spaces.Dec()
                        GetEndIf(sb, spaces, TableGen)
                End Select


                Select Case TableGen.EditKeyPassing
                    Case EditKeyPassingEnum.Inline
                        sb.AppendLine(spaces.ToString & IfEquals("e.Row.RowType", "DataControlRowType.DataRow", TableGen))
                        spaces.Inc()
                        Select Case TableGen.CodeType
                            Case CodeTypeEnum.VB2005
                                sb.AppendLine(spaces.ToString & "Dim cmd As new Button")
                            Case CodeTypeEnum.CS2005
                                sb.AppendLine(spaces.ToString & "Button cmd = new Button();")
                        End Select

                        sb.AppendLine(spaces.ToString & "cmd.UseSubmitBehavior = " & GetFalse(TableGen) & EndStatement(TableGen))
                        sb.AppendLine(spaces.ToString & "cmd.Text = ""Edit""" & EndStatement(TableGen))
                        sb.AppendLine(spaces.ToString & "cmd.Attributes.Add(""class"", ""GridEditButton"")" & EndStatement(TableGen))
                        sb.AppendLine(spaces.ToString & "cmd.Attributes.Add(""onclick"", ""GridClick("" " & OperatorConcatenate(TableGen) & " e.Row.Cells" & OperatorNumericIndex(TableGen, "0") & ".Text " & OperatorConcatenate(TableGen) & " ""); return false;"")" & EndStatement(TableGen))
                        sb.AppendLine(spaces.ToString & "e.Row.Cells" & OperatorNumericIndex(TableGen, "e.Row.Cells.Count - 1") & ".Controls.Add(cmd)" & EndStatement(TableGen))
                        spaces.Dec()
                        GetEndIf(sb, spaces, TableGen)
                    Case Else

                End Select
                spaces.Dec()
                GetEndSub(sb, spaces, TableGen)
        End Select
    End Sub

    Public Shared Sub ASPXUpdateHiddenFields(ByVal spaces As Space, ByVal sb As StringBuilder, ByVal TableGen As RawCreateScript)
        If TableGen.DevelopmentMode = DevelopmentMode.Development Then
            sb.AppendLine(HTMLComment("[ASPXUpdateHiddenFields]"))
        End If
        Select Case TableGen.EditKeyPassing
            Case EditKeyPassingEnum.Inline
                sb.AppendLine(spaces.ToString() & "<div class=""hidden"">")
                spaces.Inc()
                For Each Column As PCGColumn In TableGen.Columns
                    If Column.IsDisplayColumn = True Then
                        If Column.IsCheckBoxColumn Then
                            sb.AppendLine(spaces.ToString & "<" & Column.ControlTypeName & " id=""" & Column.ControlName() & """ runat=""server""></" & Column.ControlTypeName & ">")
                        Else
                            sb.AppendLine(spaces.ToString & "<asp:TextBox id=""" & Column.ControlName() & """ runat=""server""></asp:TextBox>")
                        End If

                    End If
                Next
                spaces.Dec()
                sb.AppendLine(spaces.ToString() & "</div>")
        End Select

    End Sub


End Class